1

When I store data as a JSON variable, I can normally create variables from it in JS like this:

var person = {"name":"adam"};
var name = person.name;

When I use the fetch API though to load the resource, I am unable to create variables from the data in this same way. I know the data has loaded though as I can log it and browse it in the console.

I am currently trying to do this with the following:

  var person;
        fetch(url)
          .then(res => res.json())
          .then(data => person = data)

            var name = person.name

Assuming that the (url) loads the same data as above, how would I set the 'name' variable as the 'name' field in the json file?

1
  • 1
    You do it within the then function. In the space where you currently have "var name=person.name" the fetch and associated promises have not yet executed so those values will be undefined. Commented Nov 12, 2020 at 18:27

2 Answers 2

4

fetch is asynchronous call and you are assigning name outside of then. so it will not work as intended. try :-

var person, name;
    fetch(url)
      .then(res => res.json())
      .then(data => {
           person = data;
           name = person.name;
       })

Note :- I have declared name globally with person, you can change its scoping accordingto your need. but it will be available after that async call

Sign up to request clarification or add additional context in comments.

Comments

2

Because there are two asynchronous steps involved, you can use the following approach with async await:

(async () => {
    const person = await (await fetch(url)).json();
    const name = person.name
    console.log( name );
    //other code needing person object
})();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.