StunkStunk
Async

Configure Query

Set global defaults for all async chunks and mutations.

configureQuery() sets global defaults that apply to every asyncChunk and mutation in your app. Per-chunk and per-mutation options always override these defaults.

import { configureQuery } from "stunk/query";

configureQuery({
  query: {
    staleTime: 30_000,
    retryCount: 3,
    refetchOnWindowFocus: true,
    onError: (err) => toast.error(err.message),
    onSuccess: (data) => analytics.track("fetch_success"),
  },
  mutation: {
    onError: (err) => toast.error(err.message),
    onSuccess: () => toast.success("Done!"),
  },
});

Call configureQuery() once at app entry — before any asyncChunk or mutation is created. Chunks read global config at creation time.


Options

query

Defaults applied to all asyncChunk instances:

OptionTypeDefaultDescription
staleTimenumber0ms before data is considered stale
cacheTimenumber300_000ms to cache after last subscriber leaves
refetchIntervalnumberAuto-refetch interval in ms
refetchOnWindowFocusbooleanfalseRefetch when window regains focus
retryCountnumber0Retries on failure
retryDelaynumber1000ms between retries
onError(error) => voidCalled when all retries are exhausted
onSuccess(data) => voidCalled after every successful fetch

mutation

Defaults applied to all mutation instances:

OptionTypeDescription
onError(error) => voidCalled on mutation failure
onSuccess(data) => voidCalled after successful mutation

Per-chunk override

Per-chunk options always take precedence over global defaults:

configureQuery({ query: { retryCount: 3 } });

// This chunk retries once — overrides the global 3
const userChunk = asyncChunk(fetchUser, { retryCount: 1 });

// This chunk uses the global 3
const postsChunk = asyncChunk(fetchPosts);

Query and mutation independently

Both query and mutation are fully optional — configure only what you need:

// Only configure query defaults
configureQuery({
  query: { staleTime: 60_000, retryCount: 2 },
});

// Only configure mutation defaults
configureQuery({
  mutation: { onError: (err) => logger.error(err) },
});

In React apps

Call once at app entry before rendering:

// main.ts / index.ts
import { configureQuery } from "stunk/query";

configureQuery({
  query: {
    staleTime: 30_000,
    onError: (err) => toast.error(err.message),
  },
  mutation: {
    onError: (err) => toast.error(err.message),
  },
});

// Then render your app
ReactDOM.createRoot(document.getElementById("root")!).render(<App />);

Testing

Use resetQueryConfig() in afterEach to prevent config bleed between tests:

import { resetQueryConfig } from "stunk/query";
import { afterEach } from "vitest";

afterEach(() => {
  resetQueryConfig();
});

What's next?

On this page