TanStackT
TanStack2w ago
11 replies
hurt-tomato

Anyway to track pending state per mutation?

hello everybody im working on a live search feature where im running a mutation getting back some data manually entering it into a querycache using setQueryData setting querydefaults for staletime and gcTime

now the issue is i have a toggle system for time! so im getting live search results for "today" / "week"

when i toggle from today -> week it triggers a new mutation and shows the loading spinner while its pending but when i switch back to today from "week" it still shows the spinner for isPending for the "week" mutation when my desired behavior is to show the cached data i got back for "today" while the "week" mutation continues on!

heres some code ive got

const handleTimeChange = (newTime) => {
    if (newTime === time) return; // do nothing if same

    if (!keywordFilters?.length) {
      setTime(newTime); // still update UI state if you want
      return;
    }
    setTime(newTime);

    const cacheKey = [
      "liveSearch",
      isAuth?.id,
      {
        keywords: [...keywordFilters].sort(),
        time: newTime,
      },
    ];

    const cached = queryClient.getQueryData(cacheKey);
    const state = queryClient.getQueryState(cacheKey);

    if (cached && state?.status === "success" && !state.isInvalidated) {
      // Use cached results
      setResults(cached.results);
      setKeywordFilters(cached.keywords);
      setTime(cached.time);
    } else {
      // Trigger mutation if cache missing or stale
      liveSearchMutation.mutate({
        keywords: keywordFilters,
        time: newTime,
        limit: 15,
      });
    }
  };


heres my handle time change function to trigger the mutation when time changes but when i flip back and cache exists for previous one and the other mutation is still running i want it to show the old data

how can i achieve that?
Was this page helpful?