Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda