DEV Community

CodeBucks
CodeBucks

Posted on • Edited on

5 1

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.

import React, { useState, useEffect } from "react";
function FetchAPI() {
//Get Method
const apiGet = () => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
console.log(json);
});
};
return (
<div>
My API <br />
<button onClick={apiGet}>Fetch API</button>
<br />
</div>
);
}
export default FetchAPI;
view raw FetchAPI.js hosted with ❤ by GitHub

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:

import React, { useState, useEffect } from "react";
function FetchAPI() {
const [data, setData] = useState([]);
//Get Method
const apiGet = () => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
return (
<div>
My API <br />
<button onClick={apiGet}>Fetch API</button>
<br />
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default FetchAPI;
view raw FetchAPI.js hosted with ❤ by GitHub

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:

import React, { useState, useEffect } from "react";
function FetchAPI() {
const [data, setData] = useState([]);
//Get Method
const apiGet = () => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
return (
<div>
My API <br />
<button onClick={apiGet}>Fetch API</button>
<br />
{/* <pre>{JSON.stringify(data, null, 2)}</pre> */}
<div>
<ul>
{data.map((item) => (
<li key={item.id}>
{item.userId},{item.title}
</li>
))}
</ul>
</div>
</div>
);
}
export default FetchAPI;
view raw FetchAPI.js hosted with ❤ by GitHub

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 😉

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay