I've had this issue for a long time but finally need to solve it. I have a payload that I cycle through via "next" and "previous" buttons. When these are clicked, a param in the URL is changed which triggers a hook to fetch data with that new param value.
The issue is when I do this it fetches the current/old data (wrong) as well as the new data (correct). Any idea why it would do this? Here's a snippet...
Cycle.tsx (the next/previous cmp which updates the URL with the new param value. This works fine)
const match = useRouteMatch();
const history = useHistory();
const onPreviousClick = () => {
const previousItem = data[foundItemPosition - 1];
if (previousItem) {
const path = generatePath(match.path, { ...match.params, carId: previousItem.carId });
history.replace(path);
}
}
const onNextClick = () => {
const nextItem = data[foundItemPosition + 1];
if (nextItem) {
console.log("key: ", nextItem.carId) // This is correct
const path = generatePath(match.path, { ...match.params, carId: nextItem.carId });
history.replace(path);
}
}
PageView.tsx
const { carId } = useParams<CarPageParams>();
useGetCar(carId); // This fetches the car with the NEW param value but ALSO the old one as well!?
useGetCar = () => {
const response = useQuery([CarQueryKeys.GET_CAR, carId], getCar, {
refetchOnWindowFocus: true,
enabled: carId,
onError: (data: any) => { dispatch(notifications(data?.message, NOTIFICATION_ERROR)); },
});
return response;
Thanks all! I really don't understand why it's fetching with the old and new param values when it should just be the new value. I've been on this for ages now.
What ever the issue I had ages ago was different, but I've resolved this now. It turns out the react-query library has a
refetchOnWindowFocus
property which defaults to true. Needless to say, it was making the same call again on window focus before then making the correct one (hence API call x2). I toggled this property to false and it's only making the necessary call now.