Is there a way to refetch the data when the ponent 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 e 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>
)}
Is there a way to refetch the data when the ponent 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 e 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>
)}
Share
Improve this question
asked Oct 21, 2021 at 12:35
SoleSole
3,35818 gold badges71 silver badges134 bronze badges
1
- Similar question is answered stackoverflow./questions/62587993/… – Ram Rana Commented Oct 21, 2021 at 12:52
1 Answer
Reset to default 3With your setup, if you fetch your data, move to another view and e back (at least 5 seconds later) it will refetch - if you navigate and e back BEFORE those 5 seconds - it should not.
If you want to prevent re-fetching when you consider data not being 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