T
TanStack2y ago
wise-white

empty data on refetch error

I have a simple useQuery that on success shows the correct data, but on error is returning empty.
const {data, error, isLoading} = useQuery({
queryKey: ['time-entries'],
queryFn: () =>
fetch(`${process.env.NEXT_PUBLIC_URL}/api/time-entires?userId=${session?.user.id}`).then(resp =>
resp.json(),
),
refetchInterval: 1000 * 10, // Refetch every 10 seconds
})
const {data, error, isLoading} = useQuery({
queryKey: ['time-entries'],
queryFn: () =>
fetch(`${process.env.NEXT_PUBLIC_URL}/api/time-entires?userId=${session?.user.id}`).then(resp =>
resp.json(),
),
refetchInterval: 1000 * 10, // Refetch every 10 seconds
})
If the example api returns a 500 the data is now an object with error in it. However I would like to keep the previous data (was a feature in v4 I believe). This query is inside a custom hook and just returns
return [data?.timeEntries ?? [], isLoading]
return [data?.timeEntries ?? [], isLoading]
Since the hook returns data.timeEntires it then defaults to [] since timeEntires doesn't exist on the error data object. @tanstack/react-query - ^5.18.1
2 Replies
other-emerald
other-emerald2y ago
I think the problem is that fetch does not raise an error on 500 Either implement it or use axios, ky, etc

Did you find this page helpful?