Can manage to understand optimistic update.

Hello there,
I'm trying to implement optimistic update in my application but I struggle a bit. Here is my function :

  const addCardToCollection = ({
    card,
    collectionId,
    userId,
  }: {
    card: Database['public']['Tables']['cards']['Row']
    collectionId: Database['public']['Tables']['collections']['Row']['id']
    userId: string
  }) => {
    const queryClient = useQueryClient()
    const { mutate } = useMutation({
      mutationFn: async () => {
        const res = await cardToCollection({
          cardId: card.id,
          collectionId,
          userId,
        })
        // ---^ Return an object with count/data/error/status/statusText properties

        return res
      },
      onMutate: async data => {
        await queryClient.cancelQueries(['view_collection'])

        console.log(data)
        // ----------^ Return undefined
      },
      onSettled: () => {
        queryClient.invalidateQueries({ queryKey: ['view_collection'] })
      },
    })

    return {
      mutate,
    }
  }


Few questions:
- Do we agree than the onMutate function will be called before the mutationFn ?
- Where are the data parameter on the onMutate function comes from ?
Was this page helpful?