How to load a random quote from API using an event (onLoad or other) in ReactJS?

Viewed 54

I'm making a simple random quote generator. Here is my code so far:

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

function App() {
  const [quote, setQuote] = React.useState({
    text: "",
    author: "",
  });
  const [allQuotes, setAllQuotes] = React.useState([]);

  React.useEffect(() => {
    fetch("https://type.fit/api/quotes")
      .then((res) => res.json())
      .then((data) => setAllQuotes(data));
  }, []);

  function getQuote() {
    const randomNumber = Math.floor(Math.random() * allQuotes.length);
    const text = allQuotes[randomNumber].text;
    const author = allQuotes[randomNumber].author;

    setQuote((prevQuote) => ({
      ...prevQuote,
      text: text,
      author: author,
    }));
  }

  return (
    <div className="App">
      <p>{quote.text}</p>
      <p>{quote.author}</p>

      <button onClick={getQuote}>New quote</button>
    </div>
  );
}

export default App;

The problem is that I do not how to load a page with a quote already. The button works, it's OK but I want to have a quote from the start. I tried different things, like onLoad event:

<div className="App" onLoad={getQuote}>

but it doesn't work.

1 Answers

You can use another useEffect hook that sets quote when allQuotes is populated:

const {useState, useEffect} = React;

function App() {
  const [quote, setQuote] = useState({
    text: "",
    author: "",
  });
  const [allQuotes, setAllQuotes] = useState([]);

  useEffect(() => {
    fetch("https://type.fit/api/quotes")
      .then((res) => res.json())
      .then((data) => setAllQuotes(data));
  }, []);
  
  // useEffect to set 'quote' on change of 'allQuotes' value
  useEffect(() => {
    if(allQuotes.length) getQuote();
  }, [allQuotes]);
  
  function getQuote() {
    const randomNumber = Math.floor(Math.random() * allQuotes.length);
    const text = allQuotes[randomNumber].text;
    const author = allQuotes[randomNumber].author;

    setQuote((prevQuote) => ({
      ...prevQuote,
      text: text,
      author: author,
    }));
  }

  return (
    <div className="App">
      <p>{quote.text}</p>
      <p>{quote.author}</p>

      <button onClick={getQuote}>New quote</button>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Related