reactjstypescriptreact-hooksreact-queryreact-custom-hooks

React Query Conditional Fetch Data from API not work


I want to fetch data based on a custom hook in react query.

if (filter == "NEW") {
  const { data, isLoading } = useGetConsultasByStatusQueryDate({
    status: "NEW",
    queryDate: allTimeDateQuery(),
  });
}

but shows the next error:

React Hook "useGetConsultasByStatusQueryDate" is called conditionally. React Hooks must be called in the exact same order in every component render.

The custom hook is:

export const useGetConsultasByStatusQueryDate = (query: {
  status: string;
  queryDate: string;
}) => {
  return useQuery({
    queryKey: ["consultas", { query }],
    queryFn: async () => {
      const consultas = await getQueryFetch(CONSULTAS_URI, query);
      return consultas as Consultas | undefined;
    },
  });
};

How can I fetch data conditionally using React-Query?


Solution

  • Conditionally calling React hooks breaks the Rules of Hooks.

    You appear to want to only make the query request when the status is "NEW". For this you can specify when the useQuery hook should be enabled, and unconditionally call the custom query hook. See Disabling/Pausing Queries for more details.

    Example Implementations: