0

I'm experiencing some weird behaviour in JS that I've never experienced before. I'm trying to make an API call to get a users profile, however, the variable doesn't seem to get defined. This is my API call

axios.get('http://127.0.0.1:8000/api/v1/profile/',{
  headers: {
    Authorization: `Token ${token}`
  }
}).then(response => {
  var userProfile = response.data
  console.log(userProfile)
})

Everything above works normally fine, however, when I try to access the variable userProfile the chrome console says it's undefined. For example the following code gives an undefined error:

axios.get('http://127.0.0.1:8000/api/v1/profile/',{
  headers: {
    Authorization: `Token ${token}`
  }
}).then(response => {
  var userProfile = response.data
})
console.log(userProfile)

I thought that declaring a variable with var I could access it outside the function call and I even defined userProfile = null initially and then tried changing it but the value didn't seem to change. Any help would be appreciated.

electro7912
  • 339
  • 4
  • 14
  • I think you need to export the variable for that. userProfile is local variable here. Declare it beforehand or export it. – Hasit Bhatt Sep 02 '18 at 11:26
  • Two problems: 1. As of the `console.log`, the ajax call will still be outstanding. (As someone likes to say here on SO: You can't eat the pizza before it's delivered.) See the linked question's answers for details. 2. You've declared `userProfile` within your callback, so naturally it's a local variable within that callback. You need to address both problems (by just using it from the callback, see linked question's answers). – T.J. Crowder Sep 02 '18 at 11:27

0 Answers0