DEV Community

Cover image for Fetching and rendering data from an API in React.js
Luqman Shaban
Luqman Shaban

Posted on

Fetching and rendering data from an API in React.js

Introduction

Working with data has become a vital aspect of modern web apps, and knowing how to work with data can make you stand out from other developers. In this article, we’ll be covering the topic by creating a quote generator web application. You can view the live app here , and for those interested in the code, the GitHub repo is available here

Set-up

  1. create a new React app
  2. Install the dependencies: npm i axios react-icons
  3. set up tailwind CSS (Optional) I’ll be using it for styling follow this guide to set it up

Implementation

In your App.js file, import the following dependencies:

import { useEffect, useState } from 'react';
import axios from 'axios';
import { ImQuotesLeft, ImQuotesRight } from 'react-icons/im'
Enter fullscreen mode Exit fullscreen mode

create two states inside the App component:

const [quotes, setQuotes] = useState([])
const [randomQuote, setRandomQuote] = useState()
Enter fullscreen mode Exit fullscreen mode

The quotes state will store the quotes retrieved from the dummy API while the randomQuote will store the quote to be rendered.

To send a request to the API, let’s create an asynchronous function:

const getQuotes = async () => {
    try {
      const response = await axios.get('https://dummyjson.com/quotes')
      setQuotes(response.data.quotes)
    } catch (error) {
      console.error(error);
    }
  }
Enter fullscreen mode Exit fullscreen mode

Create a function that will pick a random quote from the array of quotes

const generateRandomQuote = () => {
    const randomIndex = Math.floor(Math.random() * quotes.length)
    setRandomQuote(quotes[randomIndex])
    console.log(quotes[randomIndex]);
  }

Enter fullscreen mode Exit fullscreen mode

The variable randomIndex generates a random index to select a quote from the quotes array
setRandomQuote(quotes[randomIndex]) sets the randomQuote state to the quote at the randomly chosen index from the code before it.

  1. Call the getQuotes method
useEffect(() => {
    getQuotes()
  },[])
Enter fullscreen mode Exit fullscreen mode
  1. Create the button

Inside the div container, create a button that will generate a random and add a click event:

return (
    <div className="md:p-32 px-10 flex items-center justify-center flex-col gap-y-20 bg-black w-full h-[100vh] font-sans">
      <button onClick={generateRandomQuote} className='text-white border border-white  p-2 rounded-lg hover:text-black hover:bg-white transition ease-in-out duration-75'>Generate Quote</button>
    </div>
  );

Enter fullscreen mode Exit fullscreen mode
  1. Rendering the random quote
return (
    <div className="md:p-32 px-10 flex items-center justify-center flex-col gap-y-20 bg-black w-full h-[100vh] font-sans">
      {randomQuote &&
        <article className='bg-slate-200 shadow-md shadow-slate-50 md:w-auto w-full-10 h-auto rounded-xl p-10 text-black'>
          <p className='flex items-start md:flex-row flex-col gap-x-2 bg-slate-400 p-2 rounded-md shadow-md font-medium mb-3'>
            <ImQuotesLeft /> 
            {randomQuote.quote} 
            <ImQuotesRight />
          </p>
          <p className='text-gray-500 font-bold'>{randomQuote.author}</p>
        </article>
      }
      <button onClick={generateRandomQuote} className='text-white border border-white  p-2 rounded-lg hover:text-black hover:bg-white transition ease-in-out duration-75'>Generate Quote</button>
    </div>
  );

Enter fullscreen mode Exit fullscreen mode
  • In the above code, we conditionally rendered random { randomQuote && <article></article>} this part ensures that the quote only renders when the randomQuote state has a value assigned to it to prevent errors and optimize performance.
    Inside the article, the first

    element renders the random quote. <ImQuotesLeft /> and <ImQuotesRight /> are the quote icons from the react-icon library.
    {randomQuote.quote} renders the actual quote itself. If you run the app and the browser's console, you'll see the following data from the API:
    {id: 4, quote: 'Two roads diverged in a wood, and I—I took the one…raveled by, And that has made all the difference.', author: 'Robert Frost'}
    It's an Object with the keys id, quote, and author. Hence the randomQuote.quote.

  • The second <p> tags, renders the Author's name, in the same manner, the elements before it did by accessing the value of the the author from the Object:{randomQuote.author}

  • Final Code:
    This is how the file looks:

import { useEffect, useState } from 'react';
import axios from 'axios';
import { ImQuotesLeft, ImQuotesRight } from 'react-icons/im'

function App() {
  const [quotes, setQuotes] = useState([])
  const [randomQuote, setRandomQuote] = useState()

  const getQuotes = async () => {
    try {
      const response = await axios.get('https://dummyjson.com/quotes')
      setQuotes(response.data.quotes)
    } catch (error) {
      console.error(error);
    }
  }

  const generateRandomQuote = () => {
    const randomIndex = Math.floor(Math.random() * quotes.length)
    setRandomQuote(quotes[randomIndex])
    console.log(quotes[randomIndex]);
  }

  useEffect(() => {
    getQuotes()
  },[])
  return (
    <div className="md:p-32 px-10 flex items-center justify-center flex-col gap-y-20 bg-black w-full h-[100vh] font-sans">
      {randomQuote &&
        <article className='bg-slate-200 shadow-md shadow-slate-50 md:w-auto w-full-10 h-auto rounded-xl p-10 text-black'>
          <p className='flex items-start md:flex-row flex-col gap-x-2 bg-slate-400 p-2 rounded-md shadow-md font-medium mb-3'>
            <ImQuotesLeft /> 
            {randomQuote.quote} 
            <ImQuotesRight />
          </p>
          <p className='text-gray-500 font-bold'>{randomQuote.author}</p>
        </article>
      }
      <button onClick={generateRandomQuote} className='text-white border border-white  p-2 rounded-lg hover:text-black hover:bg-white transition ease-in-out duration-75'>Generate Quote</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion
In this article, we’ve explored the fascinating world of web development and data manipulation by creating a quote generator web application. We began by emphasizing the increasing importance of working with data in modern web applications, highlighting the significance of this skill for developers. I hope the article helped.

Happy coding!

GitHub Repo

Join our community by subscribing to the newsletter to receive regular updates, fresh insights, and exclusive content.

Let’s Connect:
LinkedIn
Website

Top comments (0)