TanStackT
TanStack13mo ago
7 replies
awake-maroon

refetchOnWindowFocus seems to be getting ignored sometimes

Hi all! I am having an issue with my tanstack query useQuery hook. This is for a fully client-side SPA app, in Typescript React with Vite under the hood.

I have a file where I lay out all of the queries with the query options; the one in question:

export const camps = (getToken: GetToken) => ({
  get: (id?: string) =>
    queryOptions<CampEvent>({
      queryKey: ["camp", id],
      queryFn: async () => {
        // biome-ignore lint/style/noNonNullAssertion: checked by enabled
        const { url, method } = API_ROUTES.GET_CAMP(id!);
        const response = await customFetch(getToken, url, { method });
        if (!response.ok) throw new Error("Failed to fetch camp");
        return response.json();
      },
      enabled: !!id && id !== "new",
    }),


And on the Create/Edit page, this is how said hook is used, for the scenario to load the data into the form:

  // Query existing camp if editing
  const campQuery = useQuery({
    ...camps(getToken).get(id),
    select: (data) => {
      // omitted for brevity
    },
    refetchOnWindowFocus: false,
    staleTime: Number.POSITIVE_INFINITY,
  });

  const form = useForm<CampCreateForm>({
    resolver: zodResolver(campCreateForm),
    mode: "all",
    defaultValues: {
      admin_share: 35,
      teaching_teams: [],
      session_timings: [],
      class_assignments: [],
    },
    values: id && id !== "new" ? campQuery.data : undefined,
  });


The issue with this is that the refetchOnWindowFocus option seems to sometimes be ignored. In the screen recording you will see a video of me clicking back and forth changing the focus, and about 1 in every 4 clicks it refetches the data and resets the form. this could be an issue as the user would lose their data if they needed to click away in the form.

I tried to create a minimal reproduction but was unable to.
Was this page helpful?