1

Using the Fetch API I'm making a GET request to an API endpoint which returns an object. I would like to save this object to use later, outside of the Fetch, but it seems that when I do, the variable I've initialized returns undefined.

I have initialized a variable before the fetch which I set equal to the response data inside a .then call:

const getObject = (convoId) => {
  let url = base_url + `/${convoId}`
  let convo;    //<-- initializing the variable

  fetch(url, { method: "GET", headers })
  .then(response => response.json())
  .then(data => convo = data)
  .then(() => console.log(convo)) //<-- successfully logs the data
  .catch(err => {
    console.error(err);
  });

  console.log(convo);     //<-- logs undefined
};

Because I initialized convo before the fetch and assigned it the value of the data object from the response, I expected that convo would be assigned - especially because logging convo within the .then call was successful.

But it appears it is only valid inside the fetch. I'm probably overlooking something small, so any helpful feedback is very welcome!

akorn3000
  • 289
  • 1
  • 4
  • 13
  • I am still new to javascript and I know this is old and I am sure you found your solution, but for others who are looking, this call is async, so the data is probably coming after you already console out the convo var – Tanner Summers Mar 31 '20 at 18:04

0 Answers0