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?
2
Answers
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 theuseQuery
hook should be enabled, and unconditionally call the custom query hook. See Disabling/Pausing Queries for more details.Example Implementations:
Using the
query.status
property:Adding and passing an
enabled
property:useQuery has enabled option. Rewrite your custom hook like this:
Usage of the custom hook: