Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-query - refetch data when component mounts

Is there a way to refetch the data when the component mounts? At the moment with react-router if I navigate around my app it fetches the data once and then if I navigate away and come back the data is still the old one and not a new request?

I have not wrapped my fetch call in useEffect.

const fetchInfo = async () => {
        const res = await fetch(`/api/${id}`);
        return res.json();
    };

    const { data, status } = useQuery('tableInfo', fetchInfo, {
        staleTime: 5000,
    });

using as:

{status === 'error' && (
                <div className="mt-5">Error fetching data!</div>
            )}
            {status === 'loading' && (
                <div className="mt-5">Loading data ...
                   
                </div>
            )}
            {status === 'success' && (
                <div className="mt-5">
                    <p>Result will be here</p>
                </div>
            )}
like image 404
Sole Avatar asked Nov 14 '25 11:11

Sole


1 Answers

With your setup, if you fetch your data, move to another view and come back (at least 5 seconds later) it will refetch - if you navigate and come back BEFORE those 5 seconds - it should not.

If you want to prevent re-fetching when you consider data not becoming stale over time (or not so quickly anyway), set staleTime to more than just 5 seconds (up to Infinity)

If you want to re-fetch data on every navigation to that view - don't set staleTime at all

like image 199
Emzaw Avatar answered Nov 17 '25 09:11

Emzaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!