react-querystate-managementswrtanstackreact-query

How distinguish between initialData and fetched data?


I have the following query:

export const useCurrentUser = () => {
  const enabled = !isGuestUser();

  return useQuery({
    queryKey: ['currentUser'],
    queryFn: () => getCurrentUser(),
    gcTime: Infinity,
    initialData: enabled
      ? (jwtDecode(localStorage.getItem('token') as string) as User)
      : ({} as User),
    enabled,
    refetchOnWindowFocus: false,
  });
};

Initial Data is taken from localStorage and is very limited - I want to distinguish between initialData and the later fetched full data. How to do this?

EDIT

export const useCurrentUser = () => {
  const enabled = !isGuestUser();

  return useQuery({
    queryKey: ['currentUser'],
    queryFn: () => getCurrentUser(),
    gcTime: Infinity,
    initialData: enabled
      ? (jwtDecode(localStorage.getItem('token') as string) as User)
      : ({} as User),
    enabled,
    refetchOnWindowFocus: false,
  });
};

When use initialData , useQuery typescript returns User, but when use placeholderData, it is User | undefined.


Solution

  • From the documentation:

    IMPORTANT: initialData is persisted to the cache, so it is not recommended to provide placeholder, partial or incomplete data to this option and instead use placeholderData

    So you should probably just swap out your initialData for placeholderData and you can check isPlaceholderData alongside isSuccess in the useQuery result to see what state you're in.

    e.g.

    const { data, error, isSuccess, isError, isPlaceholderData } = useQuery({ ... });