Hello All, In this tutorial we will learn How to make REST API calls in React JS. It means we use fetch API to get data in React with REST API.
To get the data from the server we will use the REST API available for free. We will use the fetch() method to request the URL & get the response from the server. The fetch API uses promises which will add a plus point.
Table of Contents
Steps for React JS Fetch API Example
- Step 1: Create a new React Project
- Step 2: HTTP Request & Response
- Step 3: Update UI
- Step 4: Run Application
- Step 5: Output
Read this also
React native
Step 1: Create a new React Project
To demonstrate the working of fetch() API, We need to create a new React Project. Use the below command to create a new project in react
npx create-react-app myapp
Now, go to our project path
cd myapp
We will open this project in Visual Studio Code editor using the below command.
code .
Step 2: HTTP Request & Response
We are going to fetch the data from the JSON placeholder site which gives us a demo API. If you want to call your own API then that is also ok. Just you need to make some changes according to your response.
Now, we will import useState to initiate the state of the component & useEffect which is similar to the componentDidMount() method.
The fetch() function is as shown below
const fetchData = () => {
fetch(URL)
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getData(response);
})
}
here, URL is nothing but
const URL = 'https://jsonplaceholder.typicode.com/posts';
Step 3: Update UI
Now, It’s time to show the data after fetching it successfully from the server. So, We will use the list component to show our response.
return (
<>
<h1>How to call REST API in React JS</h1>
<ul>
{data.map((item, i) => {
return <li key={i}>{item.title}</li>
})}
</ul>
</>
);
Full Source Code
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [data, getData] = useState([])
const URL = 'https://jsonplaceholder.typicode.com/posts';
useEffect(() => {
fetchData()
}, [])
const fetchData = () => {
fetch(URL)
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getData(response);
})
}
return (
<>
<h1>How to call REST API in React JS</h1>
<ul>
{data.map((item, i) => {
return <li key={i}>{item.title}</li>
})}
</ul>
</>
);
}
export default App;
Step 4: Run Application
Now, We have to run our application in the browser to see the output. Use the below command to run the react application.
npm start
Step 5: Output

1 thought on “MAKE REST API CALLS IN REACT JS”