Optimistic Updates

Similiar to tRPC, each query function has a useUtils method, so lets say we import a server action we created using createCaller called serverQuery1

UseUtils

import { serverQuery1 } from '~/server/etc'
const serverQueryUtils = serverQuery1.useUtils()

serverQueryUtils.cancel() // cancel
serverQueryUtils.invalidate() // invalidate
serverQueryUtils.setData(...) // set query data
serverQueryUtils.getData(...) // get query data

Usage

import { serverQuery1, serverMutation1 } from '~/server/etc'

const MyComponent = () => {
  const listPostQuery = serverQuery1()
  const serverQueryUtils = serverQuery1.useUtils()

  const postCreate = serverMutation1(() => ({
    async onMutate(newPost) {
      // Cancel outgoing fetches (so they don't overwrite our optimistic update)
      await serverQueryUtils.cancel()

      // Get the data from the queryCache
      const prevData = serverQueryUtils.getData()

      // Optimistically update the data with our new post
      serverQueryUtils.setData(undefined, (old) => [...old, newPost])

      // Return the previous data so we can revert if something goes wrong
      return { prevData }
    },
    onError(err, newPost, ctx) {
      // If the mutation fails, use the context-value from onMutate
      serverQueryUtils.setData(undefined, ctx.prevData)
    },
    onSettled() {
      // Sync with server once mutation has settled
      serverQueryUtils.invalidate()
    },
  }))
}