0
Fork 0
mirror of https://github.com/TanStack/query.git synced 2026-11-18 19:33:22 +00:00
query/docs/framework/angular/guides/optimistic-updates.md
Josh a2151d28e1
feat(query-core): add context to mutationfn & mutation callbacks (#9615)
* feat(query-core): add context to mutationfn

Co-Authored-By: travikk <627275+travikk@users.noreply.github.com>

* fix(query-core): mutation onSuccess scope param should also be undefined

Co-Authored-By: travikk <627275+travikk@users.noreply.github.com>

* feat: add scope deprecate context on mutation state

* feat(query-core): add mutation context to all mutation callbacks

* chore: pr amends

Co-Authored-By: Dominik Dorfmeister <1021430+TkDodo@users.noreply.github.com>

* test(unit): update to handle context in mutation callbacks

* chore: rename to onMutateResult

* chore: revert context deprecation on MutationState

---------

Co-authored-by: travikk <627275+travikk@users.noreply.github.com>
Co-authored-by: Dominik Dorfmeister <1021430+TkDodo@users.noreply.github.com>
Co-authored-by: Dominik Dorfmeister <office@dorfmeister.cc>
2025-09-16 10:22:43 +02:00

4.2 KiB

id title ref replace
optimistic-updates Optimistic Updates docs/framework/react/guides/optimistic-updates.md
React useMutation hook useMutationState addTodoMutation
Angular injectMutation function injectMutationState addTodo
addTodo = injectMutation(() => ({
  mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
  // make sure to _return_ the Promise from the query invalidation
  // so that the mutation stays in `pending` state until the refetch is finished
  onSettled: async () => {
    return await queryClient.invalidateQueries({ queryKey: ['todos'] })
  },
}))
@Component({
  template: `
    @for (todo of todos.data(); track todo.id) {
      <li>{{ todo.title }}</li>
    }
    @if (addTodo.isPending()) {
      <li style="opacity: 0.5">{{ addTodo.variables() }}</li>
    }
  `,
})
class TodosComponent {}
@Component({
  template: `
    @if (addTodo.isError()) {
      <li style="color: red">
        {{ addTodo.variables() }}
        <button (click)="addTodo.mutate(addTodo.variables())">Retry</button>
      </li>
    }
  `,
})
class TodosComponent {}
// somewhere in your app
addTodo = injectMutation(() => ({
  mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
  mutationKey: ['addTodo'],
}))

// access variables somewhere else

mutationState = injectMutationState<string>(() => ({
  filters: { mutationKey: ['addTodo'], status: 'pending' },
  select: (mutation) => mutation.state.variables,
}))
queryClient = inject(QueryClient)

updateTodo = injectMutation(() => ({
  mutationFn: updateTodo,
  // When mutate is called:
  onMutate: async (newTodo, context) => {
    // Cancel any outgoing refetches
    // (so they don't overwrite our optimistic update)
    await context.client.cancelQueries({ queryKey: ['todos'] })

    // Snapshot the previous value
    const previousTodos = context.client.getQueryData(['todos'])

    // Optimistically update to the new value
    context.client.setQueryData(['todos'], (old) => [...old, newTodo])

    // Return a result object with the snapshotted value
    return { previousTodos }
  },
  // If the mutation fails,
  // use the result returned from onMutate to roll back
  onError: (err, newTodo, onMutateResult, context) => {
    context.client.setQueryData(['todos'], onMutateResult.previousTodos)
  },
  // Always refetch after error or success:
  onSettled: (data, error, variables, onMutateResult, context) => {
    context.client.invalidateQueries({ queryKey: ['todos'] })
  },
}))
queryClient = inject(QueryClient)

updateTodo = injectMutation(() => ({
  mutationFn: updateTodo,
  // When mutate is called:
  onMutate: async (newTodo, context) => {
    // Cancel any outgoing refetches
    // (so they don't overwrite our optimistic update)
    await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })

    // Snapshot the previous value
    const previousTodo = context.client.getQueryData(['todos', newTodo.id])

    // Optimistically update to the new value
    context.client.setQueryData(['todos', newTodo.id], newTodo)

    // Return a result with the previous and new todo
    return { previousTodo, newTodo }
  },
  // If the mutation fails, use the result we returned above
  onError: (err, newTodo, onMutateResult, context) => {
    context.client.setQueryData(
      ['todos', onMutateResult.newTodo.id],
      onMutateResult.previousTodo,
    )
  },
  // Always refetch after error or success:
  onSettled: (newTodo, error, variables, onMutateResult, context) => {
    context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] })
  },
}))
injectMutation({
  mutationFn: updateTodo,
  // ...
  onSettled: (newTodo, error, variables, onMutateResult, context) => {
    if (error) {
      // do something
    }
  },
})