I'm using React Query to query my data and I have a hook "useDraft" that I only want to call if a condition is met.
const getDraft = useDraft;
let draft;
if (category === "drafts") {
const { data } = getDraft({
id: id,
});
draft = data;
projectId = draft && draft.projectId;
}
If I go from one place where the condition is met to another I get one of these errors (depending on which way I'm going):
Rendered more hooks than during the previous render.
or Rendered fewer hooks than expected.
Anyone who knows how can I solve this? Thanks!
As mentioned in the documentation linked in one of the comments, hooks should be called consistently (i.e. always and in the same order) inside your component and not conditionally.
You could solve it by having the hook return the draft and a function. You'd then call the hook at the top of your component and later call the function returned by the hook conditionally to load the draft.
For example (assuming the draft comes from some API):