agentleFS
charanjit-singhcharanjit-singh/lovable-skills/skills/tanstack-mutations-and-invalidation/SKILL.md

tanstack-mutations-and-invalidation

Skill10 starsChanged 6 months agoMITView on GitHub

Use when writing TanStack Query mutations: useMutation, onSuccess invalidation, optimistic updates, error rollback, or chained mutations. Not for read-only queries (use tanstack-query-alternative).

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every server write goes through useMutation.

    line 11
  2. Very specific:

    Use mutateAsync only when you need to await (e.g.

    line 42
  3. Very specific:

    Always implement onError rollback.

    line 106
  4. Very specific:

    When you must chain, use mutateAsync and try/catch:

    line 133

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

TanStack mutations and invalidation

Every server write goes through useMutation. Treat invalidation as part of the mutation contract, not an afterthought.

Companion skills: tanstack-query-alternative, optimistic-updates, api-error-handling.

Basic mutation

// src/hooks/mutations/useCreateProject.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createProject } from "@/api/projects";
import { projectKeys } from "../queries/keys";

export function useCreateProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: createProject,
    onSuccess: (newProject) => {
      qc.invalidateQueries({ queryKey: projectKeys.all });
      qc.setQueryData(projectKeys.detail(newProject.id), newProject);
    },
  });
}

Components call it cleanly:

const { mutate, isPending, error } = useCreateProject();
<Button disabled={isPending} onClick={() => mutate(values)}>Create</Button>

Use mutateAsync only when you need to await (e.g. inside a form onSubmit).


Invalidation strategies

Pick one per mutation:

StrategyWhenAPI
InvalidateLists may change shapeinvalidateQueries({ queryKey }) — marks stale, refetches what's mounted
Set dataYou already have the new valuesetQueryData(key, value) — instant, no refetch
RemoveResource is goneremoveQueries({ queryKey })
ResetWipe cache (logout, switch org)qc.clear() or resetQueries({ queryKey })

Combine when both apply: optimistically setQueryData, then invalidateQueries on settle to reconcile.

Broad invalidation by prefix

Key factories sort tuples broadest-first so a single invalidation wipes related queries:

qc.invalidateQueries({ queryKey: projectKeys.all });
// invalidates ["projects"], ["projects", "list", ...], ["projects", "detail", ...]

For partial matches, use a predicate:

qc.invalidateQueries({
  predicate: (q) => q.queryKey[0] === "projects" && q.queryKey[1] === "list",
});

Optimistic updates with rollback

export function useToggleLike(postId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () => api.toggleLike(postId),
    onMutate: async () => {
      await qc.cancelQueries({ queryKey: postKeys.detail(postId) });
      const prev = qc.getQueryData<Post>(postKeys.detail(postId));
      qc.setQueryData<Post>(postKeys.detail(postId), (p) =>
        p ? { ...p, liked: !p.liked, like_count: p.like_count + (p.liked ? -1 : 1) } : p,
      );
      return { prev };
    },
    onError: (_err, _vars, ctx) => {
      if (ctx?.prev) qc.setQueryData(postKeys.detail(postId), ctx.prev);
    },
    onSettled: () => {
      qc.invalidateQueries({ queryKey: postKeys.detail(postId) });
    },
  });
}

Rules:

  • cancelQueries before writing optimistic data — otherwise in-flight refetches will overwrite it.
  • Always implement onError rollback.
  • Reconcile with onSettled invalidation; server can change denormalized counts.

See optimistic-updates for the full UX patterns (delete-with-undo, etc.).


Error handling

Mutations should surface errors via the hook return; don't try/catch inside the hook unless you can fully recover.

const { mutate, error, isPending } = useCreateProject();

useEffect(() => {
  if (error) toast.error("Could not create project", { description: humanize(error) });
}, [error]);

Map server error slugs from api-error-handling to UI copy in a single humanize(error) helper — do not branch on error.message strings.


Sequencing and dependent mutations

For multi-step writes (e.g. create org → create project → invite members), prefer one edge function that does all three atomically and one mutation in the UI. Avoid chained mutate → onSuccess → mutate in the client — partial failures leave inconsistent state.

When you must chain, use mutateAsync and try/catch:

async function onSubmit(values: FormValues) {
  try {
    const org = await createOrg.mutateAsync(values.org);
    await createProject.mutateAsync({ orgId: org.id, ...values.project });
  } catch (e) {
    toast.error("Setup failed", { description: humanize(e) });
  }
}

Avoid

  • Mutations without an invalidation plan (lists stay stale).
  • Optimistic updates without rollback.
  • Calling qc.clear() after small mutations (nukes unrelated caches).
  • Triggering refetch storms by invalidating with no predicate from inside a high-frequency mutation.
  • onSuccess: () => window.location.reload() — defeats the cache.

Checklist

  • Invalidate or setQueryData on every mutation.
  • Optimistic mutations implement onError rollback and onSettled reconcile.
  • isPending disables the trigger.
  • Errors surfaced via hook return; mapped to UI copy via a single helper.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.