T
TanStack2y ago
ratty-blush

V5 `enabled: false` query will automatically refetch on invalidateQueries

I accidentally created queries that had the same key; one was enabled and the other was disabled. This is probably what caused the problem. I've already fixed it by changing the key of one query, but perhaps someone could verify if this is the intended behavior. Here's a small code snippet on how to reproduce it. As you can see, the query is disabled, but on the screen, you will see the 'this should never be shown' text if you click the button. "@tanstack/react-query": "5.29.2",

function useEnabledTestQuery() {
return useQuery({
queryKey: ["test"],
queryFn: async () => {
console.log("enabled:true - this is correct");
return "enabled:true - this is correct";
},
enabled: true,
});
}

function useDisabledTestQuery() {
return useQuery({
queryKey: ["test"],
queryFn: async () => {
console.log("enabled:false - this should never be shown");
return "enabled:false - this should never be shown";
},
enabled: false,
});
}

function TestComponent() {
const queryClient = useQueryClient();
const enabledTestQuery = useEnabledTestQuery();
const disabledTestQuery = useDisabledTestQuery();

return (
<div>
<button
onClick={() => {
queryClient.invalidateQueries({ queryKey: ["test"] });
}}
>
Invalidate Queries
</button>
<br />

{enabledTestQuery.data}
<br />
{disabledTestQuery.data}
</div>
);
}

function useEnabledTestQuery() {
return useQuery({
queryKey: ["test"],
queryFn: async () => {
console.log("enabled:true - this is correct");
return "enabled:true - this is correct";
},
enabled: true,
});
}

function useDisabledTestQuery() {
return useQuery({
queryKey: ["test"],
queryFn: async () => {
console.log("enabled:false - this should never be shown");
return "enabled:false - this should never be shown";
},
enabled: false,
});
}

function TestComponent() {
const queryClient = useQueryClient();
const enabledTestQuery = useEnabledTestQuery();
const disabledTestQuery = useDisabledTestQuery();

return (
<div>
<button
onClick={() => {
queryClient.invalidateQueries({ queryKey: ["test"] });
}}
>
Invalidate Queries
</button>
<br />

{enabledTestQuery.data}
<br />
{disabledTestQuery.data}
</div>
);
}
1 Reply
extended-salmon
extended-salmon2y ago
same key - different fn is basically undefined behaviour. they will overwrite each other. there can only be one queryFn for any given key

Did you find this page helpful?