0

I have a problem with custom hook from https://usehooks-ts.com/react-hook/use-fetch. When I change the page it returns the old data for a while.

function App() {
  return (
    <Router basename={process.env.PUBLIC_URL}>
      <Navbar />
      <Routes>
        <Route path='/' element={<div></div>} />
        <Route path='/coins/:id' element={<Coin />} />
      </Routes>
    </Router>
  );
}

function Navbar() {
  const [value, setValue] = useState<string>('');

  const navigate: NavigateFunction = useNavigate();

  return (
    <div>
      <input
        onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
          setValue(e.target.value);
        }}
      />
      <button onClick={() => navigate(`/coins/${value}`)}>Search</button>
    </div>
  )
};

function Coin() {
  const { id } = useParams();

  const { data, error } = useFetch<ICoin>(
    `https://api.coingecko.com/api/v3/coins/${id}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false`
  );

  console.log(id);
  console.log(data);

  if (!id || error) return <div>Error</div>

  if (!data) return <div>Loading</div>

  return (
    <div></div>
  );

};

And this is result: image

As you can see, the id has changed to ethereum from bitcoin, but the data is still old and does not become undefined immediately after changing the page.

Skyper
  • 9
  • 2
  • So is your question specifically about this `useFetch` hook? Please [edit] to clarify what specifically you need help with and to include the *relevant* code you have a problem using. See [mcve]. – Drew Reese May 04 '23 at 16:11
  • Also, from what I can read and understand of the log output, it appears that both the `id` changed from "bitcoin" to "ethereum" and that the `data` logs also changed from bitcoin to ethereum, with an undefined value between. It's unclear what the issue is. – Drew Reese May 04 '23 at 16:14
  • Shortly after the render, the data remains as it was before the page change. I would like the data to be undefined immediately after the page change – Skyper May 04 '23 at 16:24
  • The fetch for the new data needs to be initiated before the current data is updated to be undefined, so the UI taking an additional render cycle to then "see" the undefined `data` makes complete sense. – Drew Reese May 04 '23 at 16:27
  • Also, I don't know how old that `useFetch` recipe is, but I see it has some shortcomings. (1) it doesn't use any abort controller to cancel in-flight fetch requests when the component unmounts, and (2) it never invalidates cached responses, so if you've made a request on a specific URL, the response is cached, and later make another request on the same URL, the cached value is returned and new current data is never requested. Probably not what you want when querying for financial information like digital currency. – Drew Reese May 04 '23 at 16:31

0 Answers0