axios data is undefined

Issue

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?

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.

Answered By – Shariful Islam Mubin

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.