Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Adds mutation result to mutation hoc. Closes #1967 #3008

Merged
merged 8 commits into from
May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
- Adjust the `ApolloContext` definition to play a bit more nicely with
`React.createContext` types. <br/>
[@JoviDeCroock](https://github.com/JoviDeCroock) in [#3018](https://github.com/apollographql/react-apollo/pull/3018)
- The result of a mutation is now made available to the wrapped component,
when using the `graphql` HOC. <br/>
[@andycarrell](https://github.com/andycarrell) in [#3008](https://github.com/apollographql/react-apollo/pull/3008)

### Bug Fixes

Expand Down
13 changes: 10 additions & 3 deletions src/mutation-hoc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,19 @@ export function withMutation<

return (
<Mutation {...opts} mutation={document} ignoreResults>
{(mutate, _result) => {
{(mutate, { data, ...r }) => {
// the HOC's historically hoisted the data from the execution result
// up onto the result since it was passed as a nested prop
// we massage the Mutation component's shape here to replicate that
// this matches the query HoC
const result = Object.assign(r, data || {});
const name = operationOptions.name || 'mutate';
let childProps = { [name]: mutate };
const resultName = operationOptions.name ? `${name}Result` : 'result';
let childProps = { [name]: mutate, [resultName]: result };
if (operationOptions.props) {
const newResult: OptionProps<TProps, TData, TGraphQLVariables> = {
[name]: mutate,
[resultName]: result,
ownProps: props,
};
childProps = operationOptions.props(newResult) as any;
Expand All @@ -70,7 +77,7 @@ export function withMutation<
return (
<WrappedComponent
{...props as TProps}
{...childProps as any}
{...childProps as TChildProps}
/>
);
}}
Expand Down
293 changes: 147 additions & 146 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,146 +1,147 @@
import ApolloClient, {
ApolloQueryResult,
ApolloError,
FetchPolicy,
WatchQueryFetchPolicy,
ErrorPolicy,
FetchMoreOptions,
UpdateQueryOptions,
FetchMoreQueryOptions,
SubscribeToMoreOptions,
PureQueryOptions,
MutationUpdaterFn,
} from 'apollo-client';
import { MutationFn } from './Mutation';

export interface Context {
[key: string]: any;
};

export type OperationVariables = {
[key: string]: any;
};

/**
* Function which returns an array of query names or query objects for refetchQueries option.
* Allows conditional refetches.
*/
export type RefetchQueriesProviderFn = (...args: any[]) => Array<string | PureQueryOptions>;

export interface MutationOpts<TData = any, TGraphQLVariables = OperationVariables> {
variables?: TGraphQLVariables;
optimisticResponse?: TData;
refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesProviderFn;
awaitRefetchQueries?: boolean;
errorPolicy?: ErrorPolicy;
update?: MutationUpdaterFn<TData>;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
fetchPolicy?: FetchPolicy;
}

export interface QueryOpts<TGraphQLVariables = OperationVariables> {
ssr?: boolean;
variables?: TGraphQLVariables;
fetchPolicy?: WatchQueryFetchPolicy;
errorPolicy?: ErrorPolicy;
pollInterval?: number;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
partialRefetch?: boolean;
returnPartialData?: boolean;
}

export interface QueryControls<TData = any, TGraphQLVariables = OperationVariables> {
error?: ApolloError;
networkStatus: number;
loading: boolean;
variables: TGraphQLVariables;
fetchMore: (
fetchMoreOptions: FetchMoreQueryOptions<TGraphQLVariables, any> &
FetchMoreOptions<TData, TGraphQLVariables>,
) => Promise<ApolloQueryResult<TData>>;
refetch: (variables?: TGraphQLVariables) => Promise<ApolloQueryResult<TData>>;
startPolling: (pollInterval: number) => void;
stopPolling: () => void;
subscribeToMore: (options: SubscribeToMoreOptions) => () => void;
updateQuery: (mapFn: (previousQueryResult: any, options: UpdateQueryOptions<any>) => any) => void;
}

// XXX remove in the next breaking semver change (3.0)
export interface GraphqlQueryControls<TGraphQLVariables = OperationVariables>
extends QueryControls<any, TGraphQLVariables> {}

// XXX remove in the next breaking semver change (3.0)
export type MutationFunc<TData = any, TVariables = OperationVariables> = MutationFn<
TData,
TVariables
>;

export type DataValue<TData, TGraphQLVariables = OperationVariables> = QueryControls<
TData,
TGraphQLVariables
> &
// data may not yet be loaded
Partial<TData>;

// export to allow usage individually for simple components
export interface DataProps<TData, TGraphQLVariables = OperationVariables> {
data: DataValue<TData, TGraphQLVariables>;
}

// export to allow usage individually for simple components
export interface MutateProps<TData = any, TGraphQLVariables = OperationVariables> {
mutate: MutationFn<TData, TGraphQLVariables>;
}

export type ChildProps<TProps = {}, TData = {}, TGraphQLVariables = OperationVariables> = TProps &
Partial<DataProps<TData, TGraphQLVariables>> &
Partial<MutateProps<TData, TGraphQLVariables>>;

export type ChildDataProps<
TProps = {},
TData = {},
TGraphQLVariables = OperationVariables
> = TProps & DataProps<TData, TGraphQLVariables>;

export type ChildMutateProps<
TProps = {},
TData = {},
TGraphQLVariables = OperationVariables
> = TProps & MutateProps<TData, TGraphQLVariables>;

export type NamedProps<TProps, R> = TProps & {
ownProps: R;
};

export interface OptionProps<TProps = any, TData = any, TGraphQLVariables = OperationVariables>
extends Partial<DataProps<TData, TGraphQLVariables>>,
Partial<MutateProps<TData, TGraphQLVariables>> {
ownProps: TProps;
}

export interface OperationOption<
TProps,
TData,
TGraphQLVariables = OperationVariables,
TChildProps = ChildProps<TProps, TData, TGraphQLVariables>
> {
options?:
| QueryOpts<TGraphQLVariables>
| MutationOpts<TData, TGraphQLVariables>
| ((props: TProps) => QueryOpts<TGraphQLVariables> | MutationOpts<TData, TGraphQLVariables>);
props?: (
props: OptionProps<TProps, TData, TGraphQLVariables>,
lastProps?: TChildProps | void,
) => TChildProps;
skip?: boolean | ((props: TProps) => boolean);
name?: string;
withRef?: boolean;
shouldResubscribe?: (props: TProps, nextProps: TProps) => boolean;
alias?: string;
}
import ApolloClient, {
ApolloQueryResult,
ApolloError,
FetchPolicy,
WatchQueryFetchPolicy,
ErrorPolicy,
FetchMoreOptions,
UpdateQueryOptions,
FetchMoreQueryOptions,
SubscribeToMoreOptions,
PureQueryOptions,
MutationUpdaterFn,
} from 'apollo-client';
import { MutationFn, MutationResult } from './Mutation';

export interface Context {
[key: string]: any;
};

export type OperationVariables = {
[key: string]: any;
};

/**
* Function which returns an array of query names or query objects for refetchQueries option.
* Allows conditional refetches.
*/
export type RefetchQueriesProviderFn = (...args: any[]) => Array<string | PureQueryOptions>;

export interface MutationOpts<TData = any, TGraphQLVariables = OperationVariables> {
variables?: TGraphQLVariables;
optimisticResponse?: TData;
refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesProviderFn;
awaitRefetchQueries?: boolean;
errorPolicy?: ErrorPolicy;
update?: MutationUpdaterFn<TData>;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
fetchPolicy?: FetchPolicy;
}

export interface QueryOpts<TGraphQLVariables = OperationVariables> {
ssr?: boolean;
variables?: TGraphQLVariables;
fetchPolicy?: WatchQueryFetchPolicy;
errorPolicy?: ErrorPolicy;
pollInterval?: number;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
partialRefetch?: boolean;
returnPartialData?: boolean;
}

export interface QueryControls<TData = any, TGraphQLVariables = OperationVariables> {
error?: ApolloError;
networkStatus: number;
loading: boolean;
variables: TGraphQLVariables;
fetchMore: (
fetchMoreOptions: FetchMoreQueryOptions<TGraphQLVariables, any> &
FetchMoreOptions<TData, TGraphQLVariables>,
) => Promise<ApolloQueryResult<TData>>;
refetch: (variables?: TGraphQLVariables) => Promise<ApolloQueryResult<TData>>;
startPolling: (pollInterval: number) => void;
stopPolling: () => void;
subscribeToMore: (options: SubscribeToMoreOptions) => () => void;
updateQuery: (mapFn: (previousQueryResult: any, options: UpdateQueryOptions<any>) => any) => void;
}

// XXX remove in the next breaking semver change (3.0)
export interface GraphqlQueryControls<TGraphQLVariables = OperationVariables>
extends QueryControls<any, TGraphQLVariables> {}

// XXX remove in the next breaking semver change (3.0)
export type MutationFunc<TData = any, TVariables = OperationVariables> = MutationFn<
TData,
TVariables
>;

export type DataValue<TData, TGraphQLVariables = OperationVariables> = QueryControls<
TData,
TGraphQLVariables
> &
// data may not yet be loaded
Partial<TData>;

// export to allow usage individually for simple components
export interface DataProps<TData, TGraphQLVariables = OperationVariables> {
data: DataValue<TData, TGraphQLVariables>;
}

// export to allow usage individually for simple components
export interface MutateProps<TData = any, TGraphQLVariables = OperationVariables> {
mutate: MutationFn<TData, TGraphQLVariables>;
result: MutationResult<TData>;
}

export type ChildProps<TProps = {}, TData = {}, TGraphQLVariables = OperationVariables> = TProps &
Partial<DataProps<TData, TGraphQLVariables>> &
Partial<MutateProps<TData, TGraphQLVariables>>;

export type ChildDataProps<
TProps = {},
TData = {},
TGraphQLVariables = OperationVariables
> = TProps & DataProps<TData, TGraphQLVariables>;

export type ChildMutateProps<
TProps = {},
TData = {},
TGraphQLVariables = OperationVariables
> = TProps & MutateProps<TData, TGraphQLVariables>;

export type NamedProps<TProps, R> = TProps & {
ownProps: R;
};

export interface OptionProps<TProps = any, TData = any, TGraphQLVariables = OperationVariables>
extends Partial<DataProps<TData, TGraphQLVariables>>,
Partial<MutateProps<TData, TGraphQLVariables>> {
ownProps: TProps;
}

export interface OperationOption<
TProps,
TData,
TGraphQLVariables = OperationVariables,
TChildProps = ChildProps<TProps, TData, TGraphQLVariables>
> {
options?:
| QueryOpts<TGraphQLVariables>
| MutationOpts<TData, TGraphQLVariables>
| ((props: TProps) => QueryOpts<TGraphQLVariables> | MutationOpts<TData, TGraphQLVariables>);
props?: (
props: OptionProps<TProps, TData, TGraphQLVariables>,
lastProps?: TChildProps | void,
) => TChildProps;
skip?: boolean | ((props: TProps) => boolean);
name?: string;
withRef?: boolean;
shouldResubscribe?: (props: TProps, nextProps: TProps) => boolean;
alias?: string;
}
48 changes: 47 additions & 1 deletion test/client/graphql/mutations/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,55 @@ describe('graphql(mutation)', () => {
});

it('binds a mutation to props', () => {
const ContainerWithData = graphql(query)(({ mutate }) => {
const ContainerWithData = graphql(query)(({ mutate, result }) => {
expect(mutate).toBeTruthy();
expect(result).toBeTruthy();
expect(typeof mutate).toBe('function');
expect(typeof result).toBe('object');
return null;
});

renderer.create(
<ApolloProvider client={client}>
<ContainerWithData />
</ApolloProvider>,
);
});

it('binds a mutation result to props', () => {
type InjectedProps = {
result: any;
};

const ContainerWithData = graphql<{}, Data, Variables, InjectedProps>(query)(({ result }) => {
const { loading, error } = result;
expect(result).toBeTruthy();
expect(typeof loading).toBe('boolean');
expect(error).toBeFalsy();

return null;
});

renderer.create(
<ApolloProvider client={client}>
<ContainerWithData />
</ApolloProvider>,
);
});

it('binds a mutation to props with a custom name', () => {
interface Props {};

type InjectedProps = {
customMutation: any;
customMutationResult: any;
};

const ContainerWithData = graphql<Props, Data, Variables, InjectedProps>(query, { name: 'customMutation' })(({ customMutation, customMutationResult }) => {
expect(customMutation).toBeTruthy();
expect(customMutationResult).toBeTruthy();
expect(typeof customMutation).toBe('function');
expect(typeof customMutationResult).toBe('object');
return null;
});

Expand Down