How to prevent react-query from fetching initially but enables refetching?
Asked Answered
P

3

15

I'm using react-query v3.13 to fetch data from API.
What I want to do is to fetch API regularly from a certain point (for example, when clicking the start button), not from the time of calling useQuery.

I tried the following ways.

  • set enabled property to false to disable automatic querying but it also disables re-fetching.
    I could not find a way to re-enable/set the enabled property to true. And I had to use setTimeout by myself to re-fetch regularly.
  • keep enabled property as true but I could not find a way to disable the initial fetching.

Is there any proper way to do this?

Petard answered 23/3, 2021 at 3:50 Comment(1)
I remember there was the forceFetchOnMount property in the previous version, but it's replaced by refetchOnMount in version 3.Petard
C
19

if you hardcode the enabled option to false, you can still use the refetch method you get back from useQuery to imperatively trigger a fetch. But the query will still be disabled, so no background updates.

if you want a lazy that is disabled, but enables when you call a function, the best way would be with a simple abstraction over useQuery with a local state:

const useLazyQuery = (key, fn, options) => {
  const [enabled, setEnabled] = useState(false)
  return [() => setEnabled(true), useQuery(key, fn, { ...options, enabled })]
}
Cene answered 23/3, 2021 at 10:3 Comment(3)
Is there anyway to do similar using queryClient?Petard
I think you can have a disabled query and still do queryClient.refetchQueries(key) - this is similar to the refetch method returned from useQueryCene
Is there a way to prevent fetching when refetch method get called?Takahashi
R
3

For those coming to this post for disabling fetch on mount, especially in a server actions context where you are fetching initial data on the server side, the fix for me was to set refetchOnMount: false.

const { data, isLoading, refetch } = useQuery({
  queryKey: [`todo`, id],
  queryFn: () => actions.getTodo(id),
  initialData: initialTodo,
  refetchOnMount: false,
});
Repentant answered 1/8, 2024 at 19:16 Comment(0)
D
-3
import { useBoolean } from "@chakra-ui/react";
import { useQuery } from "@tanstack/react-query";

function useLazyQuery(queryKey, {queryFn, onError}) {
  const [Enable, setEnable] = useBoolean(false);

  const Get = useQuery(queryKey, {
    queryFn,
    onError: typeof onError === "function" && onError,
    enabled: Enable, // Habilitar la consulta solo si el filtro no está vacío
  });

  return { ...Get, enable: setEnable.on, disable: setEnable.off };
}

export default useLazyQuery;
Discordancy answered 29/9, 2023 at 15:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.