Mutation & Revalidation

The example below shows how you can use Nuxt's useNuxtData to update the UI after a mutation:

pages/todos.vue
<script setup lang="ts">
const { $client } = useNuxtApp()

const { data } = await $client.getTodos.useQuery(undefined);
</script>
components/NewTodo.vue
<script setup lang="ts">
import { getQueryKey } from 'trpc-nuxt/client'

const { $client } = useNuxtApp()
const previousTodos = ref([])

const queryKey = getQueryKey($client.getTodos, undefined)

// Access to the cached value of useQuery in todos.vue
const { data: todos } = useNuxtData(queryKey)

async function addTodo(payload) {
  // Store the previously cached value to restore if mutation fails.
  previousTodos.value = todos.value
  
  // Optimistically update the todos.
  todos.value.push(payload)

  try {
    await $client.addTodo.mutate(payload)
    // Invalidate todos in the background if the mutation succeeded.
    await refreshNuxtData(queryKey)
  } catch {
    // Rollback the data if the mutation failed.
    todos.value = previousTodos.value 
  }
}
</script>