HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

4) Dashboard Lesson

Using the Fetch API's Response Object

6 min to complete · By Ian Currie

In this lesson, you'll be taking a closer look at handling the response from the fetch() function. You'll learn how to parse the response, and how to handle the promise that it returns, along with some common mistakes to avoid.

Parsing JSON from the Response Object

The method that you will probably use most to read responses is json():

const fetchPromise = fetch(
	'http://demo.codingnomads.co:8080/tasks_api/users'
).then((response) => response.json());

Calling the json() method on the response object creates a promise that resolves to the parsed JSON data:

Showing the result of .then json

What Needs to be in a .then() Clause?

Once you call fetch, you are effectively bound to promises. You have moved into promise territory so any operation that returns a promise (i.e. asynchronous) will have to be handled in a .then() clause:

const fetchPromise = fetch('http://demo.codingnomads.co:8080/tasks_api/users')
	.then((response) => response.json())
	.then((json) => {
		const firstPerson = json[0];
		const name = firstPerson.first_name;
		console.log(name);
	});

Here, fetch() returns a promise because it's an asynchronous operation, so the next operation needs to be in a .then() clause. Then response.json() also returns a promise, so the next operation needs to be in a .then() clause. After that, none of the operations return a promise, so they don't need to be in a .then() clause.

Common Mistakes when Using Fetch

You might be tempted to write the code like this:

const fetchPromise = fetch('http://demo.codingnomads.co:8080/tasks_api/users')
	.then((response) => response.json())
	.then((json) => json[0])
	.then((firstPerson) => firstPerson.first_name)
	.then((name) => console.log(name));

Which will work, but it's not necessary, and will confuse anyone that's familiar with promises. They might ask: "Is indexing the JSON data an asynchronous operation?" The answer is no, it's not! Any operation that doesn't return a promise, and is therefore not asynchronous, doesn't need to be in a .then() clause.

If you don't wrap things in a .then() clause, then you are not handling the promise correctly. You are not waiting for the promise to resolve before moving on to the next operation. This is a common mistake:

const fetchPromise = fetch(
	'http://demo.codingnomads.co:8080/tasks_api/users'
).then((response) => {
	const json = response.json();
	const firstPerson = json[0];
	const name = firstPerson.first_name;
	console.log(name);
});

This returns an error because json() returns a promise. Once you get onto the next line, you might think that json contains the JSON data. However, it actually is a promise whose internal value resolves to parsed JSON. You can't access that value until the promise resolves, which is why you have to put the next operation in a .then() clause.

This attempt to work with the promise mistakenly assumes that json has already been resolved into an actual JSON object. In fact, it's still a promise at this point.

The result of trying to log json directly

Here, the error gets thrown on the const name = firstPerson.first_name; line because you can square bracket index a promise, like you can with most objects. If the object doesn't have the key, in this case 0, then it will return undefined and not throw an error. However, you can't square bracket index the undefined value, which is why the error gets thrown there.

Once you're in promise land, you can't go back to synchronous land!

There is a lot more about the Fetch API which represents a much easier way to deal with requests than the XMLHttpRequest API, but not everything can be covered in one course. Keep the reference sources handy when you are working with it!

Summary: How to Handle Fetch API's Response Object

In this lesson, you've:

  • Recognized that the json() call on the response object returns a promise, which, once resolved, gives you the parsed JSON data.
  • Understood when to use .then() clauses.
  • Saw that not every operation needs to be in a .then() clause.
  • Noted common mistakes, like trying to treat asynchronous operations as if they were synchronous.

Keep practicing and refer back to documentation as needed!