Skip to content

Clarification Needed on Handling data for Optimistic Updates in useSWRMutation #2944

Open
vercel/swr-site
#584
@MoSattler

Description

@MoSattler

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions