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

116
Vistas
How to conditionally fetch within useEffect

I was able to fetch a new quote every time I re-render, but now I want to add a functionality where I have the option to replay the same quote and not fetch a new one if I press the replay quote button, however I still want to call the useEffect. The solution to this sounds super straight forward, however, I do not know how to approach it with useEffect in play.

Also, when using react is it better to use ref hooks, instead of document.getElementByID ?

Code SandBox Link

import "./styles.css";
import { useEffect, useState } from "react";

async function newQuote() {
  const response = await fetch("https://api.quotable.io/random");
  const data = await response.json();

  return data.content;
}

async function genQuote() {
  document.getElementById("quoteDisplay").innerText = await newQuote();
}

export default function App() {
  const [quote, fecthNewQuote] = useState(0);

  useEffect(() => {
    genQuote();

    document.getElementById(
      "newQuoteCounter"
    ).innerText = `New Quote Counter: ${quote}`;

    document.getElementById("quoteReplayedCounter").innertext = ``;
  }, [quote]);

  console.log();

  return (
    <div className="App">
      <div id="quoteDisplay"></div>
      <div id="newQuoteCounter">New Quote Counter: 0</div>
      <div id="quoteReplayedCounter"> Quote Replayed Counter: 0 </div>
      <button id="newQuoteButton" onClick={() => fecthNewQuote((c) => c + 1)}>
        Fetch New Quote
      </button>
      <button id="keepSameQuote">Keep Same Quote</button>
    </div>
  );
}

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

0

You can refactor like this with async function inside useEffect and you do not need to use these kind of document.getElementById("quoteDisplay").innerText js solutions. You can do it with react states.

Here is the working example https://codesandbox.io/embed/distracted-shamir-sfinbd?fontsize=14&hidenavigation=1&theme=dark

import "./styles.css";
import { useEffect, useState } from "react";

export default function App() {
  const [quote, fecthNewQuote] = useState(0);
  const [display, setDisplay] = useState("");

  useEffect(() => {
    async function newQuote() {
      const response = await fetch("https://api.quotable.io/random");
      const data = await response.json();
      setDisplay(data.content);
    }
    newQuote();
  }, [quote]);

  console.log();

  return (
    <div className="App">
      <div id="quoteDisplay">{display}</div>
      <div id="newQuoteCounter">New Quote Counter: {quote}</div>
      <div id="quoteReplayedCounter"> Quote Replayed Counter: 0 </div>
      <button id="newQuoteButton" onClick={() => fecthNewQuote(quote + 1)}>
        Fetch New Quote
      </button>
      <button id="keepSameQuote">Keep Same Quote</button>
    </div>
  );
}
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