Reputation: 8240
I am calling an API which in turns gives me data back. When I am trying to store that data in variable and then console.log, the result is undefined
. Why is it happening? How to fix this?
someService.js
getItems: () => {
axios.get('https://jsonplaceholder.typicode.com/users/')
.then( response => {
console.log(response.data); //gives me an array of 10 items
return response.data;
})
}
someReducer.js
case "GET_ITEM_LIST": {
let data = getItemsAPI.getItems();
console.log(data); //gives undefined
return {
...state,
items: data
}
}
Upvotes: 0
Views: 134
Reputation: 5786
You need to return promise and await for result as its async. Notice return before axios that returns promise that you can work on. (I'm editing in mobile and I guess formatting is bad. If it worked, will update later)
getItems: () => {
return axios.get('https://jsonplaceholder.typicode.com/users/')
.then( response => {
console.log(response.data); //gives me an array of 10 items
return response.data;
})
}
Then, await getItems()
or getItems().then()
wherever you need.
Upvotes: 1
Reputation: 2280
With your case, you fetching API from server as asynchronous
:
Try to you async/await
like this:
export default {
fetch: async (state, { type, payload }) => {
// ....
case "GET_ITEM_LIST": {
let data = await getItemsAPI.getItems();
console.log(data); // you will see data here
return {
...state,
items: data
}
}
// ....
}
}
Upvotes: 1