Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't log my JSON data, gives me "undefined" while logging in App.js

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    });
};

>Solution :

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);
    });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading