How to fetch REST API data in React

In this tutorial, we will learn how to fetch REST API data and use it in react components by building a book catalogue page.Setting up a React app

Execute the following commands to set up a React app: $ npx create-react-app my_cool_app $ cd my_cool_app $ npm start

Copy the following code to /src/index.js

import React from 'react'; import ReactDOM from 'react-dom/client'; function MyApp() { return <h1> Books Available </h1>; } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

Check the app at http://127.0.0.1:3000/

Building an user interface for book catalogue.

Modify the MyApp function to show some demo books:

function MyApp() { const demo_books = [ { "id": -1, "name": "Book-Name", "author": "Author-Name" }]; const books = demo_books; // TODO: add useState() here. const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); }

Make the books variable the component’s state.

Replace the books variable initialization line with the following useState code.

// Need: import { useState } from 'react'; const [books, setBooks] = useState(demo_books)

Creating a REST API URL

Create a file book.json inside the /public directory. Add the following content to the file.


[
    {
        "id": 1,
        "name": "Code Complete",
        "author": "Steve McConnell"
    },
    {
        "id": 2,
        "name": "The Pragmatic Programmer",
        "author": "Andrew Hunt"
    },
    {
        "id": 3,
        "name": "Programming Pearls",
        "author": "Jon L. Bentley"
    }
]

You can access the books.json at http://127.0.0.1:3000/books.json

Use fetch api to retrieve REST API data.

Add the following fetch api code after the useState() code.

// Need: import { useEffect } from 'react'; useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); // empty-brackets to fetch data only once.

MyApp will get executed every time the state of the component changes. useEffect with zero-dependency will fetch the data only once. If you don’t use useEffect, the change of the books-state by fetch api will invoke the MyApp function, which contains the fetch api code. This cycle will retrieve the REST data an indefinite number of times.

If you define another state which influences the data (say total_books) , you should use the second argument to specify it so that the data will be fetched every time that state changes:  useEffect( _ , [total_books]); 

Your app will show the following output:

 

Books Available
  • Code Complete by Steve McConnell
  • The Pragmatic Programmer by Andrew Hunt
  • Programming Pearls by Jon L. Bentley

 

Here goes the complete code:

import React from 'react'; import ReactDOM from 'react-dom/client'; import { useState, useEffect } from 'react'; function MyApp() { const [books, setBooks] = useState([]) useEffect(() => { fetch('/books.json') .then(response => response.json()) .then(setBooks); }, []); const content = books.map( p => { return ( <li key={p.id}> <b> { p.name } </b> by <i> { p.author } </i> </li> ) }); return ( <div> <h1> Books Available </h1> <ul> { content } </ul> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<MyApp />);

 


Thanks for coming by 🙂


My Thought

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

Our Tool : hike percentage calculator