How to access data in mounted() with nuxt.js - javascript

I tried to do a for loop inside a mounted() function with nuxt.js. The data I tried to loop through was called with axios in created() but when I log the data in created() I get this object:
[__ob__: Observer]
mounted:
mounted() {
// creating FeaturedCasinos
for(let i = 0; i > this.casinos.length; i++) {
console.log("loop")
if(this.casinos[i].brand_tags[2].Brand_Tag_Name = "Featured") {
this.featuredCasinos.push(this.casinos[i]);
}
}
},
created:
created() {
return axios.get("http://xxx.xxx.xxx.xx/casinos/").then(res2 => (this.casinos = res2.data))
}
EDIT:
asyncData({ params }) {
return axios.get(casinoURL + params.casinos).then(res => {
return {
casino: res.data,
casinoID: res.data[0].id,
casinoBonus: res.data[0].bonuses,
casinoPros: res.data[0].brand_pros,
casinoCons: res.data[0].brand_cons,
casinoGames: res.data[0].verticals,
casinoTags: res.data[0].brand_tags,
casinoPayments: res.data[0].payment_methods,
casinoDeposits: res.data[0].Deposit_Methods,
casinoWithdrawals: res.data[0].Withdrawal_Methods,
casinoLanguages: res.data[0].languages,
casinoGamingProvider: res.data[0].gaming_provider,
casinoAnswers: res.data.map(item => { return {FAQ_Answer_One:item.FAQ_Answer_One, FAQ_Answer_Two:item.FAQ_Answer_Two, FAQ_Answer_Three:item.FAQ_Answer_Three, FAQ_Answer_Four:item.FAQ_Answer_Four, FAQ_Answer_Five:item.FAQ_Answer_Five, FAQ_Answer_Six:item.FAQ_Answer_Six}})
};
})
},
asyncData({ params }) {
return axios.get("http://xxx.xxx.xxx.xx/casinos/").then(res2 => {
return { casinos: res2.data }
});
},

As per the documentation:
You do NOT have access to the component instance through this inside asyncData because it is called before initializing the component.
So instead in asyncData you should return the data that will be merged with the component data as an object:
asyncData({ params }) {
return axios.get("http://xxx.xxx.xxx.xx/casinos/").then(res2 => {
return { casinos: res2.data }
}
}
EDIT: in this new case after you edited the question you should delete one of the asyncData and retrieve the unified data. You may use the async/await syntax to make the code more clear and easier to read:
asyncData({ params }) {
const res = await axios.get(casinoURL + params.casinos)
const res2 = await axios.get("http://xxx.xxx.xxx.xx/casinos/")
return {
casino: res.data,
casinoID: res.data[0].id,
casinoBonus: res.data[0].bonuses,
casinoPros: res.data[0].brand_pros,
casinoCons: res.data[0].brand_cons,
casinoGames: res.data[0].verticals,
casinoTags: res.data[0].brand_tags,
casinoPayments: res.data[0].payment_methods,
casinoDeposits: res.data[0].Deposit_Methods,
casinoWithdrawals: res.data[0].Withdrawal_Methods,
casinoLanguages: res.data[0].languages,
casinoGamingProvider: res.data[0].gaming_provider,
casinoAnswers: res.data.map(item => { return {FAQ_Answer_One:item.FAQ_Answer_One, FAQ_Answer_Two:item.FAQ_Answer_Two, FAQ_Answer_Three:item.FAQ_Answer_Three, FAQ_Answer_Four:item.FAQ_Answer_Four, FAQ_Answer_Five:item.FAQ_Answer_Five, FAQ_Answer_Six:item.FAQ_Answer_Six}})
casinos: res2.data
}
}

Related

How to pass more parameters in useInfiniteQuery?

I am using React query useInfiniteQuery to get more data
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", listofSessions, {
getNextPageParam: (lastPage, pages) => {
if (lastPage.length < 10) return undefined;
return pages.length + 1;
},
});
API requests:
const listofSessions = async ({ groupId, pageParam = 1 }) =>
await axios
.get(`${apiURL}/groups/allsessions`, {
params: {
groupId: 63,
page: pageParam,
},
})
.then((res) => {
return res.data.data;
});
I want to pass groupId to listofSessions API function like that:
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", listofSessions({groupId}), ....
But I get an error
Missing queryFn
How can I solve this problem of passing multiple parameter values in useInfiniteQuery?
Does passing a new function work?
const listofSessions = async ({ groupId, pageParam = 1 }) =>
await axios
.get(`${apiURL}/groups/allsessions`, {
params: {
groupId: 63,
page: pageParam,
},
})
.then((res) => {
return res.data.data;
});
// pass a new function
const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", ({ pageParam = 1 }) => listofSessions({ groupId, pageParam}), {
getNextPageParam: (lastPage, pages) => {
if (lastPage.length < 10) return undefined;
return pages.length + 1;
},
});
Edit: Please include dependencies in the query key InfiniteQuery(["listofSessions", groupId, moreSearchParams], so that the cache is valid for the search parameters. Thanks #TkDodo for pointing it out and improving the answer
If it is possible to refer to groupId inside listofSessions that would be a simpler solution.

What is the best way to call a function and render a child component onClick in React?

I have the below code, I want to call a function and render a child component onCLick. What is the best way to achieve this?
import AddOrder from './AddOrder'
return (
<Button onClick={handleCheckout}>Checkout</Button>
)
const handleCheckout = () => {
<AddOrder />
fetch("http://localhost:5000/create-checkout-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
items: data?.getUser ? data.getUser.cart : cart,
email: currentUser ? currentUser.email : undefined,
}),
})
.then(async (res) => {
if (res.ok) return res.json();
const json = await res.json();
return await Promise.reject(json);
})
.then(({ url }) => {
window.location = url;
})
.catch((e) => {
console.error(e.error);
});
};
I tried making a new function called handleAll and adding it like this:
function handleAll(){
handleCheckout()
<AddOrder />
}
AddOrder.js:
function AddOrder() {
const d = new Date();
let text = d.toString();
const { currentUser } = useContext(AuthContext);
const { data, loading, error } = useQuery(queries.GET_USER_BY_ID, {
fetchPolicy: "cache-and-network",
variables: {
id: currentUser.uid
},
});
const [addOrder] = useMutation(queries.ADD_ORDER);
useEffect(() => {
console.log('hi')
})
if(error) {
return <h1> error</h1>;
}
if(loading) {
return <h1> loading</h1>;
}
if (data){
let newCart = []
for(let i=0; i< data.getUser.cart.length; i++){
newCart.push({quantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id})
}
console.log(newCart)
addOrder({
variables: {
userId: currentUser.uid, status: 'ordered', createdAt: text, products: newCart
}
});
console.log("hello")
}
}
export default AddOrder;
This did not work either. When I reload this it add 3 copies of the same order to the mongodb collection. What is the right way to do this?

Why can't I access this variable from the state VUEX 4

I of course tried it with out the state.groupCrud.group and still no go. Is my syntax correct. I am using vuejs3 i will provide some screenshots of the object.
This is the State Object:
const state = () => ({
group: {}, //This is the one i am trying to access.
groups: [],
loading: false,
error: null,
success: false,
});
I am getting the data from api like this:
async getGroup({ commit }, id) {
try {
await commit('axiosSingleDataBegin');
const query = await DataService.get(`/groups/unique/${id}`);
await commit('axiosSingleDataSuccess', query.data.data.group);
} catch (err) {
await commit('axiosSingleDataErr', err);
}
},
And I am setting it to the state like this:
axiosSingleDataSuccess(state, data) {
state.loading = false;
state.group = data;
},
This is how i am using the state
setup() {
const { state, dispatch } = useStore();
const group = state.groupCrud.group;
const { params } = useRoute();
onMounted(() => {
dispatch('getGroup', params.id);
console.log(group); //doesnt work
});
// ...
},
This is the console.log(state.groupCrud); Object
This is the console.log(state.groupCrud.group) Object
I am getting a empty Proxy object when i try to use the state.groupCrud.group although the object is not empty

How do you pass variables to other JS modules with Fetch API?

A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.
A sample JSON that will get replaced with real weather data.
dummy-data.json
{
"weather": {
"temp": 4,
"rain": 1,
"wind": 1.2
}
}
The fetch API logic.
fetchWeather.js
import { manageData} from './manageScript.js';
const DUMMY = '../dummy-data.json';
const fetchWeather = () => {
fetch(DUMMY)
.then((res) => {
return res.json();
})
.then((data) => {
manageData(data); // attaches JSON weather properties to variables
})
.catch((error) => {
console.log(error);
});
};
export { fetchWeather };
Attaches the JSON data to variables.
manageScript.js
function manageData(data) {
let rain = data.weather.rain;
//let wind = data.weather.wind;
let rainProbability;
if (rain == 1) {
rainProbability = 1;
}
else {
rainProbability = 0;
}
return rainProbability; // not sure how to return the data....?
};
export { manageData };
I want the variables from manageData function above to work here
makeSynth.js
import { manageData } from './manageScript.js';
const createSynth = () => {
//Web Audio API stuff goes here to create sounds from the variables.
//How do I get the variables to work here. Code below does not work!
let soundOfRain = manageData().rainProbability;
console.log(soundOfRain);
};
You can achieve this by refactoring your promises into a async/await pattern then returning the result (a different method of dealing with promises). Also - your createSynth function should be calling fetchWeather, not manageScript
dummy-data.json
{
"weather": {
"temp": 4,
"rain": 1,
"wind": 1.2
}
}
manageScript.js
function manageData(data) {
let rain = data.weather.rain;
//let wind = data.weather.wind;
let rainProbability;
if (rain == 1) {
rainProbability = 1;
} else {
rainProbability = 0;
}
return rainProbability;
}
export { manageData };
fetchWeather.js
import { manageData } from "./manageScript.js";
const DUMMY = "../dummy-data.json";
// Use async/await to be able to return a variable out from the promise
const fetchWeather = async () => {
const raw = await fetch(DUMMY);
const json_data = await raw.json();
const rain = manageData(json_data);
// Now you should be able to return the variable back out of the function
return rain;
};
export { fetchWeather };
makeSynth.js
import { fetchWeather } from "./fetchWeather.js";
const createSynth = async () => {
//Web Audio API stuff goes here to create sounds from the variables.
//Need to call fetchWeather (which in turn will call manageData)
let soundOfRain = await fetchWeather();
console.log(soundOfRain);
};
createSynth();
// dummy-data.json
{
"weather": {
"temp": 4,
"rain": 1,
"wind": 1.2
}
}
// fetchWeather.js
import { getRainProbability } from './get-rain-probability.js'
import { createSynth } from './create-synth.js'
const DUMMY = '../dummy-data.json'
const fetchWeather = () => {
return fetch(DUMMY)
.then((res) => res.json())
.then((data) => {
createSynth({ rainProbability: getRainProbability(data) })
})
.catch((error) => {
console.log(error)
});
};
export { fetchWeather }
// get-rain-probability.js
function getRainProbability(data) {
let rain = data.weather.rain
let rainProbability;
if (rain == 1) {
rainProbability = 1;
}
else {
rainProbability = 0;
}
return rainProbability; // not sure how to return the data....?
};
// create-synth.js
const createSynth = ({ rainProbability }) => {
const soundOfRain = //WebAPI stuff for audio using `rainProbability`
console.log(soundOfRain);
};
export { createSynth }
You can add data as a property of manageData that would return this, and access it with manageData().data; :
fetchWeather.js
const fetchWeather = () => {
fetch(DUMMY)
.then(res => {
return res.json();
})
.then(data => {
manageData.data = data; // attaches JSON weather properties to variables
})
.catch(error => {
console.log(error);
});
};
manageScript.js
function manageData() {
// ...
return this;
}
makeSynth.js
let soundOfRain = manageData().data.rainProbability;

transition from ember service in Ember.js

generateDeviceCode(response) {
let {
encryptedactivationmessage,
macvalueactivationmessage,
encryptioncounter
} = response.registerDetails;
let softtoken = this.get('softtoken');
softtoken.callSoftTokenService(
'generateDeviceCode',
macvalueactivationmessage,
encryptedactivationmessage,
encryptioncounter
)
.then(response => {
let {
deviceCode
} = response;
let userId = this.get('userId') || this.get('userPreference.userId');
let groupId = this.get('groupId') || this.get('userPreference.groupId');
let payload = {
deviceCode,
authorizationCode: this.get('memoizedFields.authorizationCode'),
tokenSerialNumber: this.get('memoizedFields.tokenSerialNumber'),
userId,
groupId,
notificationId: 'NA'
};
this.navigation.toRoute('digital.pinRegistrationFlow', {
queryParams: {
initialState: 'setPin',
data: payload
}
});
})
.catch(err => {
Logger.error(err);
});
},
When I try to go to ember route from ember service. I get the following error Cannot read property toRoute of undefined. But when I try the same code in the controller it works fine. Can anyone help me here please ?
If you are on a current-ish version of Ember you can inject the router as a service and use it to transition.
export default Ember.Service.extend({
router: Ember.inject.service(),
actions: {
doIt() {
this.get('router').transitionTo('somewhere');
}
}
});

Categories

Resources