Deadpool
Deadpool

Reputation: 8240

Data coming in Service Response but showing 'undefined' from where it is called - JavaScript | React

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

Answers (2)

Karthik R
Karthik R

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

thortsx
thortsx

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

Related Questions