T
TanStack2y ago
foreign-sapphire

Help needed in Nextjs API + react-query rejection handling approach

Hello there! For starters I'm using nextjs@14.0.3 + react-query v5 and im using the Pages routes not the app folder. In one page i'm using react-query to fetch some data I have an endpoint in domain.com/api/something where Inside i fetch something from another API but I don't want to expose it. inside the endpoint, after fetching I will return the object responses that matter for me like this:
// rest of the logic to fetch

const data: ISomething | IErrorResponse = await response.json();

if (response.status === 404) {
return res.status(404).json(data as IErrorResponse);
}

return res.status(200).json(data as ISomething);
// rest of the logic to fetch

const data: ISomething | IErrorResponse = await response.json();

if (response.status === 404) {
return res.status(404).json(data as IErrorResponse);
}

return res.status(200).json(data as ISomething);
And inside my react component im using react-query to fetch from my own API route but the problem now is that even in the case i'm returning 404 status, the react-query somehow thinks it succeeds
const { data, isLoading, status } = useQuery({
queryKey: ['something', someID],
queryFn: (): Promise<API_RESPONSE> => getSomething(someID as string),
enabled: !!someID,
});

// after that i want to check for the errors
if (status === 'error') {
console.log('no driver found');
// router.replace('/404');
}
const { data, isLoading, status } = useQuery({
queryKey: ['something', someID],
queryFn: (): Promise<API_RESPONSE> => getSomething(someID as string),
enabled: !!someID,
});

// after that i want to check for the errors
if (status === 'error') {
console.log('no driver found');
// router.replace('/404');
}
And the issue is that I see in the network tab the call is made 4 times with the 404 rejection coming back untill it finally resolves (meaning that while retries are made I'm seeing the Loading state which feels too long p.s. I know that one solution would be to disable retries for this specific call. Does this even make sense to other people? as an approach to solve this
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?