Spoosh
Plugins

Invalidation

Auto-invalidate queries after mutations

The invalidation plugin automatically refreshes related queries after mutations succeed. This keeps your UI in sync without manual refetching.

Installation

npm install @spoosh/plugin-invalidation

Usage

import { Spoosh } from "@spoosh/core";
import { cachePlugin } from "@spoosh/plugin-cache";
import { deduplicationPlugin } from "@spoosh/plugin-deduplication";
import { invalidationPlugin } from "@spoosh/plugin-invalidation";

const client = new Spoosh<ApiSchema, Error>("/api").use([
  cachePlugin({ staleTime: 5000 }),
  deduplicationPlugin(),
  invalidationPlugin(),
]);

Default Configuration

// Default: invalidate all related tags (full hierarchy)
invalidationPlugin(); // same as { defaultMode: "all" }

// Only invalidate the exact endpoint by default
invalidationPlugin({ defaultMode: "self" });

// Disable auto-invalidation by default (manual only)
invalidationPlugin({ defaultMode: "none" });

How It Works

Tags are automatically generated from the API path hierarchy:

// Query tags are generated from the path:
useRead((api) => api("users").GET());
// → tags: ["users"]

useRead((api) => api("users/:id").GET({ params: { id: 123 } }));
// → tags: ["users", "users/123"]

useRead((api) => api("users/:id/posts").GET({ params: { id: 123 } }));
// → tags: ["users", "users/123", "users/123/posts"]

Custom Tags on Queries

You can override or extend auto-generated tags using the unified tags option:

// Mode only - 'all' generates full hierarchy
const { data } = useRead(
  (api) => api("users/:id/posts").GET({ params: { id: "123" } }),
  {
    tags: "all", // ['users', 'users/123', 'users/123/posts']
  }
);

// Mode only - 'self' generates only exact path
const { data } = useRead(
  (api) => api("users/:id/posts").GET({ params: { id: "123" } }),
  {
    tags: "self", // ['users/123/posts']
  }
);

// Custom tags only - replaces auto-generated tags
const { data } = useRead((api) => api("users").GET(), {
  tags: ["custom-users", "dashboard"], // ['custom-users', 'dashboard']
});

// Mode + custom tags - 'all' mode combined with custom tags
const { data } = useRead(
  (api) => api("users/:id/posts").GET({ params: { id: "123" } }),
  {
    tags: ["all", "dashboard"], // ['users', 'users/123', 'users/123/posts', 'dashboard']
  }
);

// Mode + custom tags - 'self' mode combined with custom tags
const { data } = useRead(
  (api) => api("users/:id/posts").GET({ params: { id: "123" } }),
  {
    tags: ["self", "dashboard"], // ['users/123/posts', 'dashboard']
  }
);

When a mutation succeeds, related queries are automatically invalidated:

const { trigger } = useWrite((api) => api("users/:id/posts").POST);

await trigger({ params: { id: 123 }, body: { title: "New Post" } });
// ✓ Invalidates: "users", "users/123", "users/123/posts"
// All queries matching these tags will refetch automatically

Per-Request Invalidation

Override the default invalidation behavior for specific mutations:

const { trigger } = useWrite((api) => api("posts").POST);

// Mode only (string)
await trigger({
  body: { title: "New Post" },
  invalidate: "all", // Invalidate entire path hierarchy
});

await trigger({
  body: { title: "New Post" },
  invalidate: "self", // Only invalidate the exact endpoint
});

await trigger({
  body: { title: "New Post" },
  invalidate: "none", // No invalidation
});

// Single tag (string)
await trigger({
  body: { title: "New Post" },
  invalidate: "posts", // Invalidate only "posts" tag
});

// Multiple tags (array without mode keyword)
await trigger({
  body: { title: "New Post" },
  invalidate: ["posts", "users", "custom-tag"],
  // → Only explicit tags are invalidated
});

// Mode + Tags (array with mode keyword)
await trigger({
  body: { title: "New Post" },
  invalidate: ["all", "dashboard", "stats"],
  // → 'all' mode + explicit tags
});

await trigger({
  body: { title: "New Post" },
  invalidate: ["posts", "self", "users"],
  // → 'self' mode + explicit tags
});

// Wildcard - global refetch
await trigger({
  body: { title: "New Post" },
  invalidate: "*", // Triggers ALL queries to refetch
});

// Combined with clearCache (from @spoosh/plugin-cache)
await trigger({
  clearCache: true, // Clear all cached data
  invalidate: "*", // Then refetch all queries
});

Options

Plugin Config

OptionTypeDefaultDescription
defaultMode"all" | "self" | "none""all"Default invalidation mode when option not specified

Per-Request Options

OptionTypeDescription
invalidate"all" | "self" | "none" | "*" | string | string[]Mode ("all", "self", "none"), wildcard ("*" for global refetch), single tag, or array of tags with optional mode keyword

Invalidation Modes

ModeDescription
"all"Invalidate all tags from path hierarchy (default)
"self"Only invalidate the exact endpoint tag
"none"Disable auto-invalidation (manual only)
"*"Global refetch - triggers all queries to refetch

Understanding "all" vs "*"

These two options serve different purposes:

  • "all" - Invalidates all tags from the current endpoint's path hierarchy. If you're mutating users/123/posts, it invalidates ["users", "users/123", "users/123/posts"]. It's scoped to the mutation's path.

  • "*" - Triggers a global refetch of every active query in your app, regardless of tags. Use this sparingly for scenarios like "user logged out" or "full data sync from server".

// "all" - scoped to this mutation's path hierarchy
await trigger({ invalidate: "all" });
// If path is users/123/posts → invalidates: users, users/123, users/123/posts

// "*" - refetches ALL queries in the entire app
await trigger({ invalidate: "*" });
// Every active useRead will refetch

Examples

Nested Path Invalidation

// Creating a new post
const { trigger: createPost } = useWrite((api) => api("posts").POST);

await createPost({
  body: { title: "New Post" },
  invalidate: "all",
});
// Invalidates: ["posts"]

// Updating a specific post
const { trigger: updatePost } = useWrite((api) => api("posts/:id").PATCH);

const postId = 1;
await updatePost({
  params: { id: postId },
  body: { title: "Updated" },
  invalidate: "all",
});
// Invalidates: ["posts", `posts/${postId}`]

// Deleting a comment on a post
const { trigger: deleteComment } = useWrite(
  (api) => api("posts/:postId/comments/:id").DELETE
);

const postId = 5;
const commentId = 10;
await deleteComment({
  params: { postId, id: commentId },
  invalidate: "all",
});
// Invalidates: ["posts", `posts/${postId}`, `posts/${postId}/comments`, `posts/${postId}/comments/${commentId}`]

Mode Comparison

// Path: posts/:id/comments
const { trigger } = useWrite((api) => api("posts/:id/comments").POST);

const postId = 1;

// Mode "all" invalidates full hierarchy
await trigger({
  params: { id: postId },
  body: { text: "Great post!" },
  invalidate: "all",
});
// Invalidates: ["posts", `posts/${postId}`, `posts/${postId}/comments`]

// Mode "self" invalidates only exact endpoint
await trigger({
  params: { id: postId },
  body: { text: "Great post!" },
  invalidate: "self",
});
// Invalidates: [`posts/${postId}/comments`]

// Mode "none" invalidates nothing
await trigger({
  params: { id: postId },
  body: { text: "Great post!" },
  invalidate: "none",
});
// Invalidates: []

Combining Mode with Explicit Tags

const { trigger: createComment } = useWrite(
  (api) => api("posts/:id/comments").POST
);

const postId = 1;

// Invalidate hierarchy + specific tags
await createComment({
  params: { id: postId },
  body: { text: "Great post!" },
  invalidate: ["all", "dashboard", "user-stats"],
});
// Invalidates: ["posts", `posts/${postId}`, `posts/${postId}/comments`, "dashboard", "user-stats"]

// Invalidate self + specific tags
await createComment({
  params: { id: postId },
  body: { text: "Great post!" },
  invalidate: ["self", `posts/${postId}`, "dashboard"],
});
// Invalidates: [`posts/${postId}/comments`, `posts/${postId}`, "dashboard"]

Manual Invalidation

The plugin exposes invalidate for manually triggering cache invalidation outside of mutations. This is useful for external events like WebSocket messages or other state changes.

import { createReactSpoosh } from "@spoosh/react";

const { useRead, invalidate } = createReactSpoosh(client);

// Invalidate with string array
invalidate(["users", "posts"]);

// Invalidate with single string
invalidate("posts");

// Global refetch - triggers ALL queries to refetch
invalidate("*");

WebSocket Example

import { useEffect } from "react";
import { invalidate } from "./spoosh";

function Dashboard() {
  useEffect(() => {
    socket.on("data-changed", (tags: string[]) => {
      invalidate(tags);
    });

    // Trigger global refetch on full sync
    socket.on("full-sync", () => {
      invalidate("*");
    });

    return () => {
      socket.off("data-changed");
      socket.off("full-sync");
    };
  }, []);

  return <div>...</div>;
}

Combining with Cache Plugin

For scenarios like logout or user switching, combine invalidate: "*" with clearCache from @spoosh/plugin-cache:

const { trigger } = useWrite((api) => api("auth/logout").POST);

// Clear cache + trigger all queries to refetch
await trigger({
  clearCache: true, // From cache plugin: clear all cached data
  invalidate: "*", // From invalidation plugin: trigger all queries to refetch
});

This ensures both:

  1. All cached data is cleared (no stale data from previous session)
  2. All active queries refetch with fresh data

Combining with Deduplication

When invalidation triggers multiple queries to refetch, some may share the same endpoint. Use deduplicationPlugin to prevent duplicate network requests:

import { Spoosh } from "@spoosh/core";
import { cachePlugin } from "@spoosh/plugin-cache";
import { deduplicationPlugin } from "@spoosh/plugin-deduplication";
import { invalidationPlugin } from "@spoosh/plugin-invalidation";

const client = new Spoosh<ApiSchema, Error>("/api").use([
  cachePlugin({ staleTime: 5000 }),
  deduplicationPlugin(),
  invalidationPlugin(),
]);

On this page