DEV Community

CodeBucks
CodeBucks

Posted on • Edited on

How to use fetch() method in React

Hi there,

Let's learn how you can use fetch() method in React.
You can call API using this method and also You can use HTTP methods like GET, POST, PUT, DELETE etc.

If you prefer to watch video then you can visit or Just go through the post:

First of all, create your React app using,

npx create-react-app FetchAPI

We're going to use {JSON} Placeholder API in this tutorial to test it inside of the fetch() method.

What is Fetch API?

As mentioned in the official MDN documentation,

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers.

Fetch API returns a Promise that resolves to the Response to a particular request, whether it is successful or not.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Let's Implement fetch() method in our React App:

We're going to refer this guide of JSON placeholder API.

Let's create one method which returns us some data from url
"https://jsonplaceholder.typicode.com/posts"

  //Get Method
  const apiGet = () => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((json) => {
        console.log(json);
      });
  };
Enter fullscreen mode Exit fullscreen mode

In above method,

In the first argument of fetch method, we will give it URL from which we're going to get Data.

After that it will return us a Promise, So we will use then keyword to convert response to json after that we will log that json data using console.log().

Let's create one button to call this method.

As an output You will get 100 objects just like this:

{
  id: 1,
  title: '...',
  body: '...',
  userId: 1
}
Enter fullscreen mode Exit fullscreen mode

Let's try to set this data in state.

Create one use state and name it as data.
You can set data state in the apiGet method right after the console.log().

After setting data state we will print it on screen using,

<pre>{JSON.stringify(data, null, 2)}</pre>

Where pre stands for preformatted tag.

Full Code:

In the output you will get whole JSON response on the screen.

Now if you want to print it and use it then you can use map function just like this:

That's it for GET method. You can watch below video If you want to know more about how to use POST, PUT and DELETE method. Still if you can not understand it please feel free to give a response I will write another post for it😀.

Thanks For Reading! 😉

Feel free to visit my youtube channel:

@CodeBucks

Follow me on Twitter where I'm sharing lot's of useful resources!

@code.bucks 😉

Top comments (0)