Skip to content

Commit

Permalink
tweak useMutation
Browse files Browse the repository at this point in the history
  • Loading branch information
brainkim committed Aug 18, 2021
1 parent 73569ef commit 7b95b24
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 20 deletions.
1 change: 1 addition & 0 deletions src/react/hoc/__tests__/mutations/lifecycle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ describe('graphql(mutation) lifecycle', () => {
interface Props {
listId: number;
}

function options(props: Props) {
return {
variables: {
Expand Down
41 changes: 21 additions & 20 deletions src/react/hooks/useMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ export function useMutation<
TCache
> = {},
) => {
if (!ref.current.result.loading && !options?.ignoreResults) {

const baseOptions = { ...options, mutation };
if (!ref.current.result.loading && !baseOptions.ignoreResults) {
setResult(ref.current.result = {
loading: true,
error: void 0,
Expand All @@ -62,17 +64,21 @@ export function useMutation<

const mutationId = ++ref.current.mutationId;
const clientOptions = mergeOptions(
{ ...options, mutation },
baseOptions,
executeOptions as any,
);
return client.mutate(clientOptions).then((response) => {

return client.mutate(clientOptions).then((response) =>{
const { data, errors } = response;
const error =
errors && errors.length > 0
? new ApolloError({ graphQLErrors: errors })
: void 0;

if (mutationId === ref.current.mutationId && !options?.ignoreResults) {
if (
mutationId === ref.current.mutationId &&
!baseOptions.ignoreResults
) {
const result = {
called: true,
loading: false,
Expand All @@ -81,19 +87,18 @@ export function useMutation<
client,
};

if (
ref.current.isMounted &&
!equal(ref.current.result, result)
) {
ref.current.result = result;
setResult(result);
if (ref.current.isMounted && !equal(ref.current.result, result)) {
setResult(ref.current.result = result);
}
}

options?.onCompleted?.(data!);
baseOptions.onCompleted?.(response.data!);
return response;
}).catch((error) => {
if (mutationId === ref.current.mutationId) {
if (
mutationId === ref.current.mutationId &&
ref.current.isMounted
) {
const result = {
loading: false,
error,
Expand All @@ -102,17 +107,13 @@ export function useMutation<
client,
};

if (
ref.current.isMounted &&
!equal(ref.current.result, result)
) {
ref.current.result = result;
setResult(result);
if (!equal(ref.current.result, result)) {
setResult(ref.current.result = result);
}
}

if (options?.onError) {
options.onError(error);
if (baseOptions.onError) {
baseOptions.onError(error);
// TODO(brian): why are we returning this here???
return { data: void 0, errors: error };
}
Expand Down

0 comments on commit 7b95b24

Please sign in to comment.