T
TanStack•3y ago
ambitious-aqua

ReactQuery Data error

I am saving token in localstorage with PersistQueryClientProvider but getting error message
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["token"]
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["token"]
// useStorageQuery.ts
export const useStorageQuery = <T>(queryKey: string, initialData?: T) => {
const queryClient = useQueryClient();

const { data: token, isLoading, isError, error } = useQuery({
queryKey: [queryKey],
queryFn: (): T | undefined => {
return undefined;
},
gcTime: Infinity,
initialData: () => {
// Check if we have anything in cache and return that, otherwise get initial data
const cachedData = queryClient.getQueryData<T | undefined>([queryKey]);
if (cachedData) {
return cachedData;
}

return initialData;
},
});

const setToken = (data: T) => {
queryClient.setQueryData([queryKey], () => data);
};

return { token, setToken, isLoading, isError, error };
};
export const useStorageQuery = <T>(queryKey: string, initialData?: T) => {
const queryClient = useQueryClient();

const { data: token, isLoading, isError, error } = useQuery({
queryKey: [queryKey],
queryFn: (): T | undefined => {
return undefined;
},
gcTime: Infinity,
initialData: () => {
// Check if we have anything in cache and return that, otherwise get initial data
const cachedData = queryClient.getQueryData<T | undefined>([queryKey]);
if (cachedData) {
return cachedData;
}

return initialData;
},
});

const setToken = (data: T) => {
queryClient.setQueryData([queryKey], () => data);
};

return { token, setToken, isLoading, isError, error };
};
I know problem is

queryFn: (): T | undefined => {
return undefined;
},

queryFn: (): T | undefined => {
return undefined;
},
How to I can return undefined? or other solution?
8 Replies
deep-jade
deep-jade•3y ago
you can't return undefined. return null instead
ambitious-aqua
ambitious-aquaOP•3y ago
thanks for your quickly reply my solution is right? I only wanna persiste query with Token key this is right?
deep-jade
deep-jade•3y ago
I'd use the new persister in v5
ambitious-aqua
ambitious-aquaOP•3y ago
yup I am v5
deep-jade
deep-jade•3y ago
but also, I'd never store tokens in localstorage for security reasons 😬
ambitious-aqua
ambitious-aquaOP•3y ago
ok I have question about cookie Could you help me?
deep-jade
deep-jade•3y ago
I'm not an expert on that 🙂
ambitious-aqua
ambitious-aquaOP•3y ago
ok thanks have a nice day

Did you find this page helpful?