TanStackT
TanStack2y ago
3 replies
hurt-tomato

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


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]


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
Was this page helpful?