Categories
JavaScript Answers

How to save output to variable as an object with JavaScript Fetch API?

Spread the love

Sometimes, we want to save output to variable as an object with JavaScript Fetch API.

In this article, we’ll look at how to save output to variable as an object with JavaScript Fetch API.

How to save output to variable as an object with JavaScript Fetch API?

To save output to variable as an object with JavaScript Fetch API, we call res.json.

For instance, we write

const foo = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const obj = await res.json();
  console.log(obj);
};

foo();

to call fetch to make a get request to https://jsonplaceholder.typicode.com/posts/1.

Then we get the promise with the response body with res.json.

And we get response body with await.

Conclusion

To save output to variable as an object with JavaScript Fetch API, we call res.json.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *