Skip to content

add (and require) onMutate hook to useOptimisticMutation so logic is fully encapsulated #202

@KyleAMathews

Description

@KyleAMathews

Right now with useOptimisticMutation you write logic like:

import { useOptimisticMutation } from '@tanstack/react-db'

const Todo = () => {
  // Create the `addTodo` mutator, passing in your `mutationFn`.
  const addTodo = useOptimisticMutation({ mutationFn })

  const handleClick = () => {
    // Triggers the mutationFn
    addTodo.mutate(() =>
      // Instantly applies the local optimistic state.
      todoCollection.insert({
        id: uuid(),
        text: '🔥 Make app faster',
        completed: false
      })
    )
  }

  return <Button onClick={ handleClick } />
}

The problem with this though is it splits logic between the useOptimisticMutation hook & the .mutate call site.

If we add a onMutate hook then you could write:

import { useOptimisticMutation } from '@tanstack/react-db'

const Todo = () => {
  // Create the `addTodo` mutator, passing in your `mutationFn`.
  const addTodo = useOptimisticMutation({
    mutationFn,
    onMutate: (text) => {
      // Instantly applies the local optimistic state.
      todoCollection.insert({
        id: uuid(),
        text,
        completed: false
      })
    }
  })

  const handleClick = () => {
    // Triggers the `onMutate`
    addTodo.mutate('🔥 Make app faster')
  }

  return <Button onClick={ handleClick } />
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions