How to Use Fetch API to Get Data in React with REST API

Last updated on: by Digamber

React Fetch API example; In this quick tutorial, we will teach you how to get data from the server with the help of Fetch API in React js application.

To fetch the data from the remote server, we will use the REST API in React.

Also, you will understand how to use React hooks to deal with server requests and responses through fetch outlook.

The fetch method helps to request a URL, similarly get a response and parse it as JSON.

Ideally, the fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The only variation is that the Fetch API uses Promises, which allows a more straightforward and cleaner API.

React Fetch API Retrieve Data Example

  • Step 1: Create React Project
  • Step 2: Build Component
  • Step 3: Make GET Request with Fetch
  • Step 4: Register Component
  • Step 5: Run + Test App

Create React Project

We are going to use the create-react-app tool to generate the new react app on our system.

npx create-react-app cruise-app

Let us move into the app folder.

cd cruise-app

If you already have the app, jump on to the subsequent step.

Build Component

Next, you need a component, here in this file you will be writing code regarding the concept,

Ensure that you are building the stateless components by adding the given code into the Posts.js file.

Open components/Posts.js file also insert the provided code inside the file.

import React from 'react'
export default function Posts() {
    return (
        <div>
            
        </div>
    )
}

Make GET Request with Fetch

First, open the components/Posts.js file.

Import the useState and useEffect hooks from from ‘react’ module.

We need a REST API; if you already have one, then no problem. Otherwise, if you want a testing API, there is no better choice than the json placeholder.

Use the custom function to get the data through fetch; it returns the response that needs to be converted to json.

Using the useState hook, we are setting the initial state of the component.

The useEffect hook is working the same as the componentDidMount life cycle method does in a class component.

import React, { useState, useEffect } from 'react'
export default function Posts() {
  const [post, getPost] = useState([])
  const API = 'https://jsonplaceholder.typicode.com/posts';
  const fetchPost = () => {
    fetch(API)
      .then((res) => res.json())
      .then((res) => {
        console.log(res)
        getPost(res)
      })
  }
  useEffect(() => {
    fetchPost()
  }, [])
  return (
    <>
      <h2>React Fetch Data with REST API Example</h2>
      <ul>
        {post.map((item, i) => {
          return <li key={i}>{item.title}</li>
        })}
      </ul>
    </>
  )
}

Register Component

One more thing you have to do, eventually register the new component into the App.js primary file.

import React from 'react'
import Posts from './components/Posts'
function App() {
  return (
    <div className="container">
      <Posts />
    </div>
  )
}
export default App

Run + Test App

In the last step, we will run the application and check how the data response looks on the browser.

npm start

How to Use Fetch API to Get Data in React with REST API

Conclusion

In this compound guide, we elaborated on how to fetch data from a rest API in React js app. Moreover, we explained two significant topics of React, data fetching and react hooks.

React hooks are best for managing and processing the data in React’s functional components. On the other hand, the fetch method plays a vital role in rendering the data from the server.

We successfully combined both the concepts and inoculated them into the react mechanism.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.