Liam
Liam2w ago

Invalidating Queries

Hey! Might be being thick here but I'm implementing in an optimistic update layer and fully expected this to work:
await queryClient.invalidateQueries({ queryKey: scheduleKey });

// I compute the query key in a reusable hook
function useScheduleQueryKey() {
const api = useTRPC();
const [weekStart] = useScheduleParams();

return api.schedule.getWeek.queryKey({ weekStart });
}
await queryClient.invalidateQueries({ queryKey: scheduleKey });

// I compute the query key in a reusable hook
function useScheduleQueryKey() {
const api = useTRPC();
const [weekStart] = useScheduleParams();

return api.schedule.getWeek.queryKey({ weekStart });
}
However that won't work. You can make it work by either removing the input - so getWeek.queryKey() or by passing the key as the only arg;
queryClient.invalidateQueries(queryKey) // Have a feeling this only works becuase it seems to just invalidate any active query so this is likely a red herring
queryClient.invalidateQueries(queryKey) // Have a feeling this only works becuase it seems to just invalidate any active query so this is likely a red herring
Is there a way I can just invalidate the query based on input or am I thinking about this wrong? The query key is correct as I can use setQueryData on it fine;
queryClient.setQueryData(scheduleKey, onMutateResult.currentData);
queryClient.setQueryData(scheduleKey, onMutateResult.currentData);
1 Reply
Nick
Nick2w ago
This should do exactly what you're asking if I'm understanding correctly. A query key generated with an input also uses the input for invalidation, you can console log it to see what we're creating and reference Tanstack's docs and dev tools to understand what matches will be made. By contrast you could use pathKey() to invalidate all queries regardless of input

Did you find this page helpful?