Skip to main content

error

Description: Defines how long a mutation error is kept in the cache.

  • How To: Pass error (in milliseconds) in the useMutation options. This determines how long the error state persists before it is automatically cleared from the global mutateCache.
    // Correct: Keep error state for 10 seconds
    const { mutate, error } = useMutation({
    error: 10 * 1000,
    mutationKey: 'login-attempt'
    });

    const onLogin = () => {
    mutate(() => api.login(credentials));
    };
  • Best Practice: Use shorter durations for transient errors that should clear quickly, and longer ones for critical errors that need to be acknowledged by the user. If you're using a global error notification system that observes the mutateCache, the error TTL will control how long the error is visible to that system.
    // Avoid this: Setting a very high error TTL without a reset mechanism
    const { mutate, error, resetError } = useMutation({
    error: 60 * 60 * 1000 // 1 hour!
    });
    // The user will see this error for an hour unless you call resetError()!

Deep Dive: How error works step by step

Example:

function SubmissionForm() {
const { mutate, error } = useMutation({
mutationKey: 'form-submission',
error: 5000 // 5 seconds
});

return <button onClick={() => mutate(submitAction)}>Submit</button>;
}

What happens step by step with the timeline:

  1. t=0s: User clicks submit

    • Mutation executes and fails.
    • Error is stored in mutateCache with key 'form-submission'.
    • Error expires at: t=0s + 5s = t=5s.
  2. t=2s: Error is displayed

    • Component renders with the error object.
    • User sees the error message.
  3. t=6s: Error expires

    • DataClient or useMutation hook detects the expired error.
    • Error is cleared from the cache entry.
    • Component re-renders, and error is now null.
  4. t=10s: User navigates away and back

    • Component re-mounts.
    • Cache is checked for 'form-submission'.
    • No error found as it has already been cleared.

Key insight: The error TTL is essential for preventing stale errors from lingering in the UI. Combined with keepError: true, it ensures that critical errors survive navigation but still clear automatically after a reasonable period.