Home > other >  How to conditionally fetch within useEffect
How to conditionally fetch within useEffect

Time:05-06

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>
  );
}

CodePudding user response:

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>
  );
}
  • Related