Home > Back-end >  Can't log my JSON data, gives me "undefined" while logging in App.js
Can't log my JSON data, gives me "undefined" while logging in App.js

Time:11-04

I am trying to use my JSON data in App.js. Normally I am making my API cals in api.js and in getData(), I can log my data perfectly. It comes as object. But if I call my getData() in my App.js and assign it to a variable, it gives me "undefined". Therefore I can't even set this data to my states. I didn't understand why ? I hope you can help me.

App.js

useEffect(() => {
    getDataFunc();
    //setDropdown(data?.attributes?.items[3]?.options);
  }, []);

const getDataFunc = async () => {
    const res = await getData(); // if I just leave the console.log() which is in the getData() and just run this line without console.log(res) it is working as well for check the data
    
    console.log(res); //gives me undefined
  };

api.js

export const getData = async function () {
  await axios
    .get(
      "blabla",
      {
        headers: {
          Authorization: `blabla`,
        },
      }
    )
    .then((json) => {
      if (json && json.status === 200) {
        //console.log(json); //The console.log() function that I was mentioned in App.js, I can reach the data perfectly
        return json.data;
      }
    })
    .catch((e) => {
      console.log(e);
    });
};

CodePudding user response:

getData should return the axio response as a promise. No need to wait since waiting take place inside getDataFunc

export const getData = function () {
  return axios
    .get(
      "blabla",
      {
        headers: {
          Authorization: `blabla`,
        },
      }
    )
    .then((json) => {
      if (json && json.status === 200) {
        //console.log(json); //The console.log() function that I was mentioned in App.js, I can reach the data perfectly
        return json.data;
      }
    })
    .catch((e) => {
      console.log(e);
    });
};
  • Related