Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MoSattler opened this issue Apr 20, 2024 · 0 comments · May be fixed by vercel/swr-site#584
Open

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

MoSattler opened this issue Apr 20, 2024 · 0 comments · May be fixed by vercel/swr-site#584

Comments

@MoSattler
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant