Skip to content

Commit

Permalink
Add code example to bound mutate section
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Paulus authored and akx committed Mar 31, 2020
1 parent ae882ec commit 40232eb
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ function Profile () {
// send a request to the API to update the data
await requestUpdateUsername(newName)
// update the local data immediately and revalidate (refetch)
// NOTE: key has to be passed to mutate as it's not bound
mutate('/api/user', { ...data, name: newName })
}}>Uppercase my name!</button>
</div>
Expand Down Expand Up @@ -393,6 +394,28 @@ The SWR object returned by `useSWR` also contains a `mutate()` function that is

It is functionally equivalent to the global `mutate` function but does not require the `key` parameter.

```js
import useSWR from 'swr'

function Profile () {
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)
// NOTE: key is not required when using useSWR's mutate as it's pre-bound
mutate({ ...data, name: newName })
}}>Uppercase my name!</button>
</div>
)
}
```

### SSR with Next.js

With the `initialData` option, you pass an initial value to the hook. It works perfectly with many SSR solutions
Expand Down

0 comments on commit 40232eb

Please sign in to comment.