Skip to content

Commit

Permalink
Avoid un-necessary useMutation re-renders
Browse files Browse the repository at this point in the history
apollographql/react-apollo#3417 adjusted `useMutation` to make sure
the current `ApolloClient` instance is available in the result
returned when `useMutation` is first called. Unfortunately, the changes
in that PR are unintentionally modifying the `useState` based `result`
object directly, instead of using `setResult`. This is ultimately
leading to inconsistencies around the `client` instance sometimes
being included in the result and stored as the `previousResult`, and
other times not being included. This can then lead to infinite
loop / too many render problems caused by the
`!equal(this.previousResult, result)` check in `updateResult` always
passing, and the state continuously being updated by repeated calls
to `setResult`.

This commit adjusts the returned `useMutation` result to be a copy
of the original `useState` based `result`, which then includes the
`client` instance. This ensures the `useState` controlled `result`
object is not mutated outside of calling `setResult`, and avoids
the infinite loop / too many render issue.
  • Loading branch information
hwillson committed Jan 9, 2020
1 parent bea10f4 commit efb5bd1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Expand Up @@ -80,6 +80,12 @@
- Utilities that were previously externally available through the `apollo-utilities` package are now only available by importing from `@apollo/client/utilities`. <br/>
[@hwillson](https://github.com/hwillson) in [#5683](https://github.com/apollographql/apollo-client/pull/5683)

### Bug Fixes

- `useMutation` adjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying the `useState` based mutation result directly. <br/>
[@hwillson](https://github/com/hwillson) in [#5770](https://github.com/apollographql/apollo-client/pull/5770)


## Apollo Client 2.6.8

### Apollo Client (2.6.8)
Expand Down
6 changes: 4 additions & 2 deletions src/react/data/MutationData.ts
Expand Up @@ -42,8 +42,10 @@ export class MutationData<
public execute(result: MutationResult<TData>) {
this.isMounted = true;
this.verifyDocumentType(this.getOptions().mutation, DocumentType.Mutation);
result.client = this.refreshClient().client;
return [this.runMutation, result] as MutationTuple<TData, TVariables>;
return [
this.runMutation,
{ ...result, client: this.refreshClient().client }
] as MutationTuple<TData, TVariables>;
}

public afterExecute() {
Expand Down

0 comments on commit efb5bd1

Please sign in to comment.