Using zod with react query v5
In useQuery v4, I used to parse the response with Zod in the select function. if everything were OK, Zod would just return the data with inferred type. otherwise, it would throw the error, and the app would crash and console the detailed error. A sample is given below:
export function useGetNotifications() { const axiosPrivate = useAxiosPrivate(); return useQuery({ query key: ["notifications"], queryFn: (): Promise<NotificationsApiResponseType> => { return axiosPrivate.get(notificationsUrl); }, select: (data) => { NotificationsApiResponseTypeSchema.parse(data); return data.data; }, refetchInterval: 2000, }); }
in v5, this is not the behaviour. App crashes on wrong data but does not log the error. maybe because:
https://tanstack.com/query/v5/docs/framework/react/guides/migrating-to-v5#the-deprecated-custom-logger-has-been-removed
if I use safeParse, I get the logs but the app doesn't crash. Behaviour is the same if I change the queryFn to an async function and use Zod before returning the response.
I can easily desired behaviour by using Zod before consuming the data in the component but the Whole point of this effort is to bake in parsing inside API.