React JS: Lab#RE01-1

React
Node.js
NPM
Install guide
Author

ProtossGP32

Published

April 18, 2023

Introduction

Link to class page

Main objectives:

  • We’ll be uusing Open Library API, which is a RESTful API, to create a React app that will display a list of books
  • We will use the Axios library to make HTTP requests to the API and retrieve the data in JSON format
  • We will display the book data in a table with four fields for each book: title, year, ISBN, pages and author
  • We will also add a loading state to show the user that the app is retrieving data from the API

The lab will demonstrate how to use a RESTful API with React to build a functional web application.

Getting started

Install development environment

Follow this guide to install NVM and Node.js.

API Rest

REST (Representational State Transfer) is a software architectural style for building web services. It is based on HTTP (Hypertext Transfer Protocol) and is commonly used for creating APIs. A RESTful API allows different software applications to communicate with each other by using HTTP methods like GET, POST, PUT and DELETE to access and manipulate data.

The Open Library API is a RESTful API that provides access to the data stored in the Open Library project. The Open Library project aims to create a web page for every book ever published. The API allows developers to retrieve information about books, authors, subjects, and more.

The two Open Library API endpoints we are going to use are:

  • https://openlibrary.org/dev/docs/api/books: this endpoint provides documentation for the Open Library Books API. It includes information on how to use the API to search for books, retrieve book details, and access other book-related information
  • https://openlibrary.org/search.json?q=*&limit=100: this endpoint is used to retrieve a list of up to 100 books from the Open Library API. The q=* parameter is used to searcch for all books, and the limit=100 parameter limits the results to 100 books. The response data is in JSON format and includes information like the book title, author, publication date, and more

Create app

Creating a new React application

First, create a path for your React applications and execute the following command:

Create new React project
npx create-react-app lab-re01-1

Install required dependencies for the project

Now go to the newly created project folder and install the following dependencies:

Install dependencies
cd lab-re01-1
npm install axios

Developing the app

BookList

We’ll create a BookList component that retrieves 100 books from the Open Library API. The logic is stored in the BookList.jsx file:

BookList.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const BookList = () => {
    const [books, setBooks] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    // useEffect hook ensures that the BookList component stays connected to the Open Library API while displated on the page
    useEffect(() => {
        // Define the fetchBooks function (?)
        const fetchBooks = async () => {

            const response = await axios.get(
                'https://openlibrary.org/search.json?q=*&limit=100'
            );
            const booksData = response.data.docs;
            setBooks(booksData);
            setIsLoading(false);

        };
        // Invoke the fetchBooks function
        fetchBooks();
        // TODO: return a clean code function with cleanup code that disconnects from the Open Library API

    }, []); // No dependencies required nor values from the component used inside of those functions

    return (
        <>
            <h1>Books</h1>
            {isLoading ? (
                <p>Loading...</p>
            ) : (
                <ul>
                    {books.map((book) => (
                        <li key={book.key}>
                            <strong>Title:</strong> {book.title} <br />
                            <strong>Year:</strong> {book.publish_year} <br />
                            <strong>ISBN:</strong> {book.isbn} <br />
                            <strong>Pages:</strong> {book.number_of_pages} <br />
                            <strong>Author:</strong> {book.author_name}
                        </li>
                    ))}
                </ul>
            )}
        </>
    );
};

export default BookList;

What it basically does is:

  • Create a BookList function that asynchronously makes a request to the Open Library API and saves the retrieved books into the books variable via a useState hook
  • After that, return the HTML snipped with all books rendered as a list

Update the index.js file

With the BookList component created, we’ll add it into the index.js file, that is our app entrypoint:

BookList.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import BookList from './BookList';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
    <BookList />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Two lines are responsible of implementing the BookList component:

  • Importing BookList component
    import BookList from './BookList'
    This imports the component logic into the script
  • Rendering BookList component
    <React.StrictMode>
        <BookList />
    </React.StrictMode>
    This renders the component after the <App /> component

Launching the app

Now it’s time to launch the app. Go to the project root path and execute the following command:

Launch React app
npm start

A browser window will automatically open pointing to the default Node.js port (http://localhost:3000)