swr icon indicating copy to clipboard operation
swr copied to clipboard

Clarification Needed on Handling data for Optimistic Updates in useSWRMutation

Open MoSattler opened this issue 2 months ago • 0 comments

While implementing optimistic updates using useSWRMutation from the SWR library, I encountered an issue with the documentation available at https://swr.vercel.app/docs/mutation#optimistic-updates.

In the example provided:

import useSWRMutation from 'swr/mutation'
 
function Profile () {
  const { trigger } = useSWRMutation('/api/user', updateUserName)
 
  return (
    <div>
      <h1>My name is {data.name}.</h1>
      <button onClick={async () => {
        const newName = data.name.toUpperCase()
 
        trigger(newName, {
          optimisticData: user => ({ ...user, name: newName }),
          rollbackOnError: true
        })
      }}>Uppercase my name!</button>
    </div>
  )
}

The data variable is used but it's unclear where it comes from. Initially, I expected data to be returned from the useSWRMutation hook, similar to the usage in useSWR:

const { trigger, data } = useSWRMutation('/api/user', updateUserName)

However, this approach does not work as data in this case does not reflect the optimistic value. Could the documentation be updated to explicitly show how the optimistic data should be accessed?

MoSattler avatar Apr 20 '24 11:04 MoSattler