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 🙂


WhatsApp forward Message Wp20.ru link, is it trustworthy to click ?

No of course not , Last week onward wp20.ru link message are circulating on WhatsApp. You might get this message from friends / family circle, please don’t click it it is a virus link.It install automatically virus to you browser.unfortunately any of your trusted fried shared that Wp20.ru and you already opened that website please clear cache & cookies .if you dont know how to do that please follow this link https://support.google.com/accounts/answer/32050?hl=en&co=GENIE.Platform%3DAndroid&oco=1 and don’t forgot to restart your system after clearing cache & cookies

Almost all different antivirus vendors listed this link as Malware/Phishing/ Suspicious link. So stay away from this link, If you see a link starting with wp20.ru don’t click it..

WhatsApp forward Message Wp20.ru link

How to add a target _blank on a WordPress menu item custom links

In WordPress custom links their is already build in choice check box ‘Open link in a new tab’, but by default it is hidden you can enable that from the screen options as in the below images

If you enable that options from the screen options tab automatically a check box will come as ‘Open link in a new tab’ like below image, check that check box and save now onward your new link always open in a new tab