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!