0

i recieve some data from x API, but i am stuck between a rock, if i want to use 'states' variable into another function, for example i want to map json object like this :

of course, it shows me error, 'state is not define';

any short way to solve this problem?

//recieve data
window.onload =  async ()  => {
                const response = await fetch("x");
                const states = await response.json();
                 console.log(states);
             };

states.map(function(bra){
 // something
}
Nightcrawler
  • 943
  • 1
  • 11
  • 32
  • 1
    The request is made onload and you somehow thing it is going to be available before that? – epascarello Apr 20 '20 at 18:39
  • Even [a global variable](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) wouldn't solve your problem. – Teemu Apr 20 '20 at 18:39

1 Answers1

0

You do not need to access local variables, if you use vanilla JS you can do something like this:

const request = async () => {
           const response = await fetch("x");
           const data = await response.json();
           renderYourData(data);           
}


const renderYourData = (data) => {
           //apend your data in DOM
}


window.addEventListener('load', function() {
           request();
});

But if you use SPA framework it's no a better approach;

CuteShaun
  • 139
  • 7