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 🙂


Python string formatting

# Welcome to TutorialShore!
# Today we will discuss Formatted String Literals
# and format method of String class in python
# Let me start writing a program to greet a student with their grade.

name = “Oyster”
grade = 8.568

message = ‘Hello ‘ + name + ‘! You scored ‘ + str(grade) + ‘.’

# ideally we want a string like
message = ‘Hello name! You scored grade.’

# To use formatted string literals (also called f-strings for short),
# begin a string with f before the opening quotation mark.
# Inside the string, you can write a Python expression or variable
# wrapped by curley brackets.

message = f’Hello {name}! You scored {grade:.2f}.’ # specify format for the field 10.2f

# You can use F instead of f and F-strings work with double and triple quotes also.

# Python String has a method called format.
# Let us explore that method
message = ‘Hello {}! You scored {:.2f}.’.format( # automatic field numbering
name, grade
)

message = ‘Hello {0}! You scored {1:.2f}. Bye {0}’.format( # manual field specification
name, grade # positional arguments
)

message = ‘Hello {name}! You scored {grade:.2f}. Bye {name} :)’.format(
name=name, grade=grade # keyword arguments
)

# The studen
student = {
“name”: “Oyster”,
“grade”: 8.456,
“subject”: “CS”
}

message = ‘Hello {name}! You scored {grade:.2f} in {subject}. Bye {name} :)’.format(
name=student[‘name’], grade=student[‘grade’], subject=student[‘subject’] # keyword arguments
)

message = ‘Hello {name}! You scored {grade:.1f} in {subject}. Bye {name} :)’.format(
**student # double asterisk operator for keyword arguments
)

print(message)