Skip to content

Commit

Permalink
Fix useMutation inFlight race condition (#3841)
Browse files Browse the repository at this point in the history
Summary:
Basically #3839 but with a repro test case that fails without the fix and passes with it

Pull Request resolved: #3841

Test Plan: Added a race condition repro test case that fails without the change and passes with it

Reviewed By: rbalicki2

Differential Revision: D34959589

Pulled By: voideanvalue

fbshipit-source-id: 0f98ac2067470ab7ba0cef02e5b7941397f28407
  • Loading branch information
voideanvalue authored and facebook-github-bot committed Mar 17, 2022
1 parent 5b12920 commit eb0fc26
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
22 changes: 21 additions & 1 deletion packages/react-relay/relay-hooks/__tests__/useMutation-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ const useMutation = require('../useMutation');
const React = require('react');
const ReactTestRenderer = require('react-test-renderer');
const {createOperationDescriptor, graphql} = require('relay-runtime');
const {createMockEnvironment} = require('relay-test-utils');
const {
MockPayloadGenerator,
createMockEnvironment,
} = require('relay-test-utils');

const {useState, useMemo} = React;
let environment;
Expand Down Expand Up @@ -151,6 +154,23 @@ it('returns correct in-flight state when commit called inside render', () => {
expect(isInFlightFn).toHaveBeenCalledWith(false);
});

it('returns correct in-flight state when mutation resolves immediately', () => {
render(environment, CommentCreateMutation);
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(false);

isInFlightFn.mockClear();
// set up a resolver that will immediately resolve the mutation
environment.mock.queueOperationResolver(operation =>
MockPayloadGenerator.generate(operation),
);
ReactTestRenderer.act(() => {
commit({variables});
});
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(false);
});

it('returns correct in-flight state when the mutation is disposed', () => {
render(environment, CommentCreateMutation);
isInFlightFn.mockClear();
Expand Down
6 changes: 3 additions & 3 deletions packages/react-relay/relay-hooks/useMutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ function useMutation<TMutation: MutationParameters>(

const commit = useCallback(
(config: UseMutationConfig<TMutation>) => {
if (isMountedRef.current) {
setMutationInFlight(true);
}
const disposable = commitMutationFn(environment, {
...config,
mutation,
Expand All @@ -117,9 +120,6 @@ function useMutation<TMutation: MutationParameters>(
},
});
inFlightMutationsRef.current.add(disposable);
if (isMountedRef.current) {
setMutationInFlight(true);
}
return disposable;
},
[cleanup, commitMutationFn, environment, isMountedRef, mutation],
Expand Down

0 comments on commit eb0fc26

Please sign in to comment.