Invalidations from Mutations

Invalidating queries is only half the battle. Knowing when to invalidate them is the other half. Usually when a mutation in your app succeeds, it's VERY likely that there are related queries in your application that need to be invalidated and possibly refetched to account for the new changes from your mutation.

For example, assume we have a mutation to post a new todo:

ts
class TodoItemComponent {
  mutation = injectMutation(() => ({
    mutationFn: postTodo,
  }))
}
class TodoItemComponent {
  mutation = injectMutation(() => ({
    mutationFn: postTodo,
  }))
}

When a successful postTodo mutation happens, we likely want all todos queries to get invalidated and possibly refetched to show the new todo item. To do this, you can use injectMutation's onSuccess options and the client's invalidateQueries function:

ts
import { injectMutation } from '@tanstack/angular-query-experimental'

export class TodosComponent {
  queryClient = injectQueryClient()

  // When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
  mutation = injectMutation((client) => ({
    mutationFn: addTodo,
    onSuccess: () => {
      client.invalidateQueries({ queryKey: ['todos'] })
      client.invalidateQueries({ queryKey: ['reminders'] })

      // OR use the queryClient that is injected into the component
      // this.queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  }))
}
import { injectMutation } from '@tanstack/angular-query-experimental'

export class TodosComponent {
  queryClient = injectQueryClient()

  // When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
  mutation = injectMutation((client) => ({
    mutationFn: addTodo,
    onSuccess: () => {
      client.invalidateQueries({ queryKey: ['todos'] })
      client.invalidateQueries({ queryKey: ['reminders'] })

      // OR use the queryClient that is injected into the component
      // this.queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  }))
}

You can wire up your invalidations to happen using any of the callbacks available in the injectMutation function

Want to Skip the Docs?
Query.gg - The Official React Query Course
“This course is the best way to learn how to use React Query in real-world applications.”—Tanner Linsley
Check it out