TanStackT
TanStack2y ago
17 replies
dead-brown

Enabled sets data to undefined - solution?

Hi, having such a modal that is opened based on search params, I fetch user info and show a spinner or data after fetching. The problem appears when we close the modal - the enabled option, from what I see, immediately sets the data to undefined, and because of this, a spinner appears briefly when closing. I have no idea what to do to prevent this. Any ideas? Tanstack query v5 by the way.
export const UserModal = () => {
  const [query, setQuery] = useQueryStates(userModalParsers);

  const { data } = useQuery({
    queryKey: ['user-info', query.userId],
    staleTime: Infinity,
    refetchOnWindowFocus: false,
    enabled: Boolean(query.userId),
    queryFn: () =>
      getUserInfo({
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Enabled
        id: query.userId!
      })
  });

  return (
    <Dialog
      open={Boolean(query.userId)}
      onOpenChange={(open) => {
        if (!open) {
          void setQuery({
            userId: null
          });
        }
      }}
    >
      <DialogContent>{!data ? <Spinner /> : <p>User info</p>}</DialogContent>
    </Dialog>
  );
};


v5 has an import keepPreviousData and this partially solves the problem - data is not set to undefined, but another problem appears: We click on user JOHN, there's loading => we fetch him => close the modal => click on user ANDRE => it shows the profile of user JOHN instead of loading => after a while it's the profile of ANDRE because it has loaded
Was this page helpful?