Quote generator app using React and API

Amit PatnaikAmit Patnaik
5 min read

Introduction

In this tutorial, you will guide a step-by-step approach on how to create a quote app using React with detailed explanation. . So, let's get started!

Prerequisites

Before we embark on this coding adventure, let's make sure you have the necessary tools and knowledge. Here's what you'll need:

  1. Basic understanding of HTML, CSS, JavaScript.

  2. Node.js installed on your machine.

    You can download node from: nodejs.org/en/download

  3. Familiarity with React and its concepts.

If you meet these prerequisites, you're all set to proceed to the next step!

Setting Up the Project

To create a new React project for our to-do app, we'll use Create React App, a tool that sets up a new React project with the necessary configuration. Follow the steps below to install Create React App and create your project:

  1. Check Node.js installation: Before proceeding, ensure that Node.js is installed correctly on your machine. Open your terminal or command prompt and run the following command to check the installed Node.js version:

      node --version
    

    You should see the version number displayed. If not, please refer to the previous section on how to install Node.js.

  2. Create Vite Project: In your terminal or command prompt, run the following command to create vite project on your machine:

     npm create vite@latest
    

    Once the command starts executing, you will be prompted for a project name. Type the name of your project and click enter.

    Next, Vite will prompt you to select a framework. Select React.

    In variant, select Javascript.

  3. Install dependencies: Navigate TO the directory it creates, and install the dependencies via npm.

      npm install
    

    It sets up the project structure and installs the necessary dependencies.

  4. Run the project:

      npm run dev
    

    This command will start the development server and open your React app in a web browser. Any changes you make to your code will automatically be reflected in the browser

    Check there are no issues in project by printing Hello World in browser :

    Create a component named App with Hello WORLD in App.js file

      import React from 'react';
      import './App.css';
    
      const App = () => {
        return (
          <div className="app">
            <h2>Hello World</h2>
          </div>
        );
      }
    
      export default App;
    

    And here's the code for App.css:

      .app {
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #282c34;
        color: white;
      }
    

    You will see a Hello World output in your browser.

Creating the quote app

For creating quote app, we can update the component App in App.js.

Step 1:Add the app and

Step 1: Add the app component

import React from 'react';
import './App.css';

const App = () => {
  return (
    <div className="app">
      <div className='container'>
        <h1>Quote app</h1>
      </div>
    </div>
  );
};

export default App;

Step 2: Import the useSate. Define the state variable 'quote' using useState hook that will store all the quotes.

import React, {useState} from 'react'; //import useState
import './App.css';

const App = () => {
const [quote, setQuote] = useState(""); //useState hook
  return (
    <div className="app">
      <div className='container'>
        <h1>Quote app</h1>
      </div>
    </div>
  );
};
export default App;

Step 3: Create a getQuote() function to fetch quotes from the API.

We are using this API: https://type.fit/api/quotes which contains a list of quotes in JSON format.

In the JSON, "text" and "author" are key-value pairs representing the properties of a quote object.

Fetching quotes from the API

For fetching the quotes we can use the fetch function to send a GET request to the URL "https://type.fit/api/quotes". This URL points to a public API endpoint that provides a collection of quotes.

fetch("https://type.fit/api/quotes")

The fetch function returns a Promise that resolves to the response of the request. You can chain the then method to the returned Promise to handle the response.

We can chain two then methods after the fetch function call.

The first then converts the response to JSON.

.then((res) => res.json()

The second then method receives the parsed JSON data as an argument( (data parameter represents the parsed JSON data, which is an array of quote objects.), allowing you to access and manipulate the data.

.then((data) => {.......}

Setting a random quote

To set a random quote from fetched data we can use :

Math.floor(Math.random() * data.length

Updating the state

Then we can quote state with a selected quote using:

setQuote(data[randomNum]);

Overall function to fetch quotes

  //  function to fetch quotes from the API:-
  const getQuote = () => {
    fetch("https://type.fit/api/quotes")  // Fetch quotes from  API
      .then((res) => res.json())          // Convert the response to JSON
      .then((data) => {
        let randomNum = Math.floor(Math.random() * data.length); // Select a random quote 
        setQuote(data[randomNum]);       // Update the 'quote' state
      });
  };

Step 4: useEffect hook

The useEffect hook is used to fetch a quote when the component mounts (i.e., on the initial render). By passing an empty dependency array ([]) as the second argument to useEffect, we ensure that the effect runs only once on the initial render.

useEffect(() => {
    getQuote();
  }, []);

Step 5: Display the quotes on clicking button

/diplaying the quotes 
<p className="quote">{quote.text}</p>
 <p className="author">- {quote.author}</p>

//button   
<button className="button" onClick={getQuote}>Get Quote</button>

Step 6: Solving the initial double update of quotes.

The app works fine till now. But the problem is that quotes are updated twice after every reload.

The issue of the initial loading of quotes being updated twice can occur due to the combination of the useEffect hook and the asynchronous nature of the fetch API.

So to solve this issue we can add a loading state to indicate when the quotes are being fetched and use a useRef hook to keep track of whether it's the initial render or not.

const [loading, setLoading] = useState(true); 
const initialRender = useRef(true);
   useEffect(() => {
     if (initialRender.current) {
       initialRender.current = false;
       return;
     }
     getQuote();
   }, []);
{ loading ? (
         <p>Loading...</p>
       ) : (
         <div className="card">
           <p className="quote">{quote.text}</p>
           <p className="author">- {quote.author}</p>
         </div>
       )}

This will solve the quote update issue.

Final Output:

You can also check it here.

Conclusion

Congratulations! You have now built a quote app using API in React.

I hope you enjoyed this article, and if you have any questions, comments, or feedback, then feel free to comment here or reach out via Twitter.

Thanks for reading!

0
Subscribe to my newsletter

Read articles from Amit Patnaik directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amit Patnaik
Amit Patnaik