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.