4

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

So I want the fetch data to recall when the component mounts and refresh the component?
In react-query data re-fetches after component mount by default (aka becomes "stale" right after it was fetched). To change it and tell react-query that your data is not becoming stale that fast (then it won't be re-fetched on every component render / view change), you should define staleTime.
so if I specify staletime, to what number?
It depends on your data in fact - if you don't expect it to change over user session lifetime - you may even go for Infinity (then you would have to mutate / refetch it manually). Otherwise, set it for amount which will prevent overfetching it (again, depends on data - it may be 1 minute as well as 15 minutes)
Although I think this is something to do with react-router rather than react-query
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.