score:2

Accepted answer

in getuserprofile() you are returning this.state before your axios get request is complete. when you call getuserprofile() from page.js you are trying to access the data before it is set from your get request.


you should be returning the promise in getuserprofile() then using async/await or .then() when you call it in componentwillmount() before setting the data

getuserprofile(){
  const url = "https://somewebsite.com/api/user_profile/"
  const user_token = localstorage.getitem('access_token')
  const authstr = 'jwt '.concat(user_token);

  return axios.get(url, { headers: { authorization: authstr } })
};

async/await

async componentwillmount() {
  const userdatares = await (new vapi().getuserprofile());
  const userdata = userdatares.data;

  this.setstate({
    first_name: userdata.first_name,
    last_name: userdata.last_name,
    email: userdata.email,
    company: userdata.company,
  });

  console.log('state', this.state);
}

promise

componentwillmount() {
  new vapi().getuserprofile().then((userdatares) => {
    const userdata = userdatares.data;

    this.setstate({
      first_name: userdata.first_name,
      last_name: userdata.last_name,
      email: userdata.email,
      company: userdata.company,
    });

    console.log('state', this.state);
  });
}

Related Query

More Query from same tag