Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda