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

axios data is undefined

I’m trying to perform an axios get request.

  axios
  .get("http://10.10.0.145/api/session", {
      headers: {
          'Cookie' : user_cookie
      }
  },         
  )
  .then(res => {
  
      result = res.data;
      id_user_intervention = res.data.id;
      console.log(id_user_intervention); //IS NOT UNDEFINED

      
    })
  .catch(error => {
    console.error(error)
  })
  console.log(id_user_intervention); //IS UNDEFINED

I need to use id_user_intervention outside the axios request. I assign res.data.id to id_user_intervention, but this variable is undefined outside the axios request…how can I solve this problem?

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

>Solution :

First of all, it’s better you learn async/await on javascript. Then, try the following solution:-

const testFunction = async () => {
  let id_user_intervention = null;
  try {
    const response = await axios.get("http://10.10.0.145/api/session", {
      headers: {
        'Cookie': user_cookie
      }
    })
    id_user_intervention = response.data.id;
  } catch (err) {
    console.error(err);
  }

  return id_user_intervention;
}

const anotherFunction = async () => {
  const data = await testFunction();
  console.log(data);
}

Hope it will work properly.

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