Skip to content

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

@pelotom

Description

@pelotom

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>
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions