From efb5bd1d88d42264031b14c9f86bd04f74df0d8f Mon Sep 17 00:00:00 2001 From: hwillson Date: Thu, 9 Jan 2020 14:38:04 -0500 Subject: [PATCH] Avoid un-necessary `useMutation` re-renders 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. --- CHANGELOG.md | 6 ++++++ src/react/data/MutationData.ts | 6 ++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 865be046c80..26089645aba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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`.
[@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.
+ [@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) diff --git a/src/react/data/MutationData.ts b/src/react/data/MutationData.ts index 6421f1ca6af..c4bf867c01e 100644 --- a/src/react/data/MutationData.ts +++ b/src/react/data/MutationData.ts @@ -42,8 +42,10 @@ export class MutationData< public execute(result: MutationResult) { this.isMounted = true; this.verifyDocumentType(this.getOptions().mutation, DocumentType.Mutation); - result.client = this.refreshClient().client; - return [this.runMutation, result] as MutationTuple; + return [ + this.runMutation, + { ...result, client: this.refreshClient().client } + ] as MutationTuple; } public afterExecute() {