0

Can someone highlight the difference between these 2 code snippets in React?

window.fetch(url)
  .then((response) => {
    console.log(response.json().content);
})

and

window.fetch(url)
  .then((response) =>  response.json())
  .then((data) =>{
    console.log(data.content);
})

response contains a Java object and content is one of the fields in that object.

2nd snippet prints the correct value of content whereas 1st snippet prints undefined.

Edit: My question is not about "why response gives a Promise rather than a normal object". It is more about what are the implications of response returning a promise.

Ketan R
  • 4,039
  • 1
  • 13
  • 15
  • See https://stackoverflow.com/questions/37555031/why-does-json-return-a-promise and https://stackoverflow.com/questions/39435842/javascript-fetch-api-why-does-response-json-return-a-promise-object-instead (and the many other existing Stack Overflow questions and answers where this is already explained) – sideshowbarker Jan 29 '19 at 05:54
  • 1
    As you tagged, take a look usage of fetch-api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – Teoman shipahi Jan 29 '19 at 05:54
  • You can user console.log(response.data.content); in first snippet to work – CyberAbhay Jan 29 '19 at 06:11
  • @CyberAbhay in first snippet, console.log(response.data.content does not work. since a response is still a promise. – Ketan R Jan 30 '19 at 05:10

2 Answers2

1

The below snippet doesn't work because response.json() returns a Promise and not a simple object which is why in the second snippet it returns a correct value as you are using .then to get the value

window.fetch(url)
  .then((response) => {
    console.log(response.json().content); // response.json() is not an object but a promise and hence you can't access content from it directly
})

The second snippet is equilvalent to

window.fetch(url)
  .then((response) => {
    response.json().then((content) => console.log(content)); 
})

but an be simplified to chainable promises by returning the response.json() promise from the first .then as shown in your second snippet

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

This is because response.json() returns promise.As it returns promise, so another then is used to catch its response. More info about promises can be found here.

While using javascript fetch you need to convert response to json using response.json(). You can skip extra step of converting response to json by using axios e.g.

axios.get(url)
  .then(res => {console.log(res)})
Umair Farooq
  • 1,763
  • 13
  • 16