Skip to content

Commit

Permalink
docs: mention the fact that mutate can no longer be called as an even…
Browse files Browse the repository at this point in the history
…t listener (#464)

Co-authored-by: Jakub Michalek <[email protected]>
  • Loading branch information
Goues and Jakub Michalek authored May 7, 2020
1 parent a6c9e63 commit 2fbb004
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,37 @@ const CreateTodo = () => {
Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [Query Cache's `refetchQueries` method](#querycacherefetchqueries) method and the [Query Cache's `setQueryData` method](#querycachesetquerydata), mutations become a very powerful tool.
Note that since version 1.1.0, the `mutate` function is no longer called synchronously so you cannot use it in an event callback. If you need to access the event in `onSubmit` you need to wrap `mutate` in another function. This is due to [React event pooling](https://reactjs.org/docs/events.html#event-pooling).
```js
// This will not work
const CreateTodo = () => {
const [mutate] = useMutation(event => {
event.preventDefault()
fetch('/api', new FormData(event.target))
})

return (
<form onSubmit={mutate}>...</form>
)
}

// This will work
const CreateTodo = () => {
const [mutate] = useMutation(formData => {
fetch('/api', formData)
})
const onSubmit = event => {
event.preventDefault()
mutate(new FormData(event.target))
}

return (
<form onSubmit={onSubmit}>...</form>
)
}
```
## Invalidate and Refetch Queries from Mutations
When a mutation succeeds, it's likely that other queries in your application need to update. Where other libraries that use normalized caches would attempt to update local queries with the new data imperatively, React Query helps you to avoid the manual labor that comes with maintaining normalized caches and instead prescribes **atomic updates and refetching** instead of direct cache manipulation.
Expand Down

0 comments on commit 2fbb004

Please sign in to comment.