TanStackT
TanStack9mo ago
1 reply
dead-brown

Cached & persisted queries (react native)

I'm using react-query w/ async-storage, the cache persists and everything is working correctly except that on failed "refetch(es)" the data in cache seems to get deleted/swapped, here's what I tried to keep the cache even on failures:

Failed attempts

1:
const useCurrentUser = (enabled: boolean = true) =>
  useQuery<User>({
    queryKey: ["currentUser"],
    enabled,
    queryFn: async () => {
        const res = await xiorInstance.get("/users/me");
        return res.data.data;
    },
    placeholderData: keepPreviousData,
    staleTime: Infinity,
    gcTime: Infinity,
  });


2:
const useCurrentUser = (enabled: boolean = true) =>
  useQuery<User>({
    queryKey: ["currentUser"],
    enabled,
    queryFn: async () => {
        const res = await xiorInstance.get("/users/me");
        return res.data.data;
    },
    initialData: queryClient.getQueryData<User>(["currentUserProfile"]), // This does NOT work even tho initialData gets cached (the cache would be cleared for this specific query after the request fails, so on restart this does nothing)
    placeholderData: keepPreviousData,
    staleTime: Infinity,
    gcTime: Infinity,
  });

3. Tried both initialData & placeholderData, does NOT work

What worked


const useCurrentUser = (enabled: boolean = true) =>
  useQuery<User>({
    queryKey: ["currentUser"],
    enabled,
    queryFn: async () => {
      try {
        const res = await xiorInstance.get("/users/me");
        return res.data.data;
      } catch (error) {
        const cachedData = queryClient.getQueryData<User>(["currentUser"]);
        if (cachedData) return cachedData;
        throw error;
      }
    },
    staleTime: Infinity,
    gcTime: Infinity,
  });

This works fine but now isError will never work which'll result in bad UX.

I went thru the docs/API but couldn't find anything related, I think I'm missing something here, thanks in advance.
Was this page helpful?