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

Return a tailored mutate function with the key already applied #136

Closed
pelotom opened this issue Nov 19, 2019 · 2 comments
Closed

Return a tailored mutate function with the key already applied #136

pelotom opened this issue Nov 19, 2019 · 2 comments
Labels
feature request New feature or request

Comments

@pelotom
Copy link

pelotom commented Nov 19, 2019

Hi, great library!

It would be a nice convenience if, similar to revalidate, a mutate function were returned from useSWR which already had the key applied, e.g.

-import useSWR, { mutate } from 'swr'
+import useSWR from 'swr'

function Profile () {
- const { data } = useSWR('/api/user', fetcher)
+ const { data, mutate } = useSWR('/api/user', fetcher)

  return (
    <div>
      <h1>My name is {data.name}.</h1>
      <button onClick={async () => {
        const newName = data.name.toUpperCase()
        // send a request to the API to update the data
        await requestUpdateUsername(newName)
        // update the local data immediately and revalidate (refetch)
-       mutate('/api/user', { ...data, name: newName })
+       mutate({ ...data, name: newName }) // look ma, no key!
      }}>Uppercase my name!</button>
    </div>
  )
}
@shuding shuding added the feature request New feature or request label Nov 21, 2019
@shuding
Copy link
Member

shuding commented Dec 1, 2019

I think it will be great to merge revalidate and mutate:

revalidate(newDataOrPromise, shouldRevalidateAfterMutation = true)

const { revalidate } = useSWR('/api/user', fetcher)

// ...
revalidate()
revalidate(newData)
revalidate(newData, false)
revalidate(post)
revalidate(post, false)

@shuding
Copy link
Member

shuding commented Feb 24, 2020

Adding support in #245.

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

No branches or pull requests

2 participants