0

I would love to get the returned value of the fetch() block and make use of it in another function, I tried declaring a variable outside the fetch and assigning it in the block but that doesn't seem to give me the desired result rather it returns undefined.

fetch(apiEndpoint).then(response => {
    return response.json()
}).then(jsonFile => {
    return jsonFile
})
  • Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Aug 09 '19 at 15:54
  • This may also help: [JavaScript: How (not) to get a value “out of” a callback](https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html) – Felix Kling Aug 09 '19 at 15:59

1 Answers1

0

The code that you are trying to execute is asynchronous, that is why you see the variable outside the fetch is undefined, but, it's undefined until the request is fulfilled. What you could do is to store the value into some king of storage (like localstorage) so you will have access to it in the future.

fetch(apiEndpoint).then(response => {
    return response.json()
}).then(jsonFile => {
    localStorage.setItem('data', JSON.stringify(jsonFile))
})

Later in another function

const data = JSON.parse(localStorage.getItem('data'))

if (data !== null) {
   // use your data
}
Alejandro Garcia Anglada
  • 2,373
  • 1
  • 25
  • 41