2

So the question is pretty straightforward. Why does this work:

fetch("https://api.github.com/users/vampaynani/repos")
  .then((res) => res.json())
  .then((repos) => {
    console.log(repos);
    this.setState({ repos });
  });

But this does not:

fetch("https://api.github.com/users/vampaynani/repos").then((repos) => {
      var r = repos.json();
      this.setState({ repos: r });
    });

Here is the sandbox link for it: SandBox

Maybe my understanding is wrong, but in my eyes these look to be doing the same thing.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
mastercooler6
  • 377
  • 2
  • 16

2 Answers2

3

This is because repos.json() is a promise that needs to be resolved (awaited) before.

fetch("https://api.github.com/users/vampaynani/repos").then(async (repos) => {
      var r = await repos.json();
      this.setState({ repos: r });
});
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
2

Since repos.json() returns a Promise. It's an async function.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40