saleor-dashboard/src/mutations.tsx

50 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-08-12 11:48:09 +00:00
import { ApolloError, MutationUpdaterFn } from "apollo-client";
2019-06-19 14:40:52 +00:00
import { DocumentNode } from "graphql";
2019-08-09 10:26:22 +00:00
import React from "react";
2019-08-12 11:48:09 +00:00
import { Mutation, MutationFunction, MutationResult } from "react-apollo";
2019-08-29 10:55:56 +00:00
import { useIntl } from "react-intl";
2019-06-19 14:40:52 +00:00
import useNotifier from "./hooks/useNotifier";
2019-09-04 10:28:04 +00:00
import { commonMessages } from "./intl";
2019-06-19 14:40:52 +00:00
export interface TypedMutationInnerProps<TData, TVariables> {
children: (
2019-08-12 11:48:09 +00:00
mutateFn: MutationFunction<TData, TVariables>,
2019-06-19 14:40:52 +00:00
result: MutationResult<TData>
) => React.ReactNode;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
variables?: TVariables;
}
2019-08-12 11:48:09 +00:00
// For some reason Mutation returns () => Element instead of () => ReactNode
2019-06-19 14:40:52 +00:00
export function TypedMutation<TData, TVariables>(
mutation: DocumentNode,
update?: MutationUpdaterFn<TData>
) {
return (props: TypedMutationInnerProps<TData, TVariables>) => {
const notify = useNotifier();
2019-08-29 10:55:56 +00:00
const intl = useIntl();
2019-08-12 11:48:09 +00:00
const { children, onCompleted, onError, variables } = props;
2019-06-19 14:40:52 +00:00
return (
2019-08-12 11:48:09 +00:00
<Mutation
2019-06-19 14:40:52 +00:00
mutation={mutation}
onCompleted={onCompleted}
2019-09-04 10:28:04 +00:00
onError={(err: ApolloError) => {
notify({
text: intl.formatMessage(commonMessages.somethingWentWrong)
});
2019-06-19 14:40:52 +00:00
if (onError) {
onError(err);
}
}}
variables={variables}
update={update}
>
2019-08-12 11:48:09 +00:00
{(mutateFn, result) => <>{children(mutateFn, result)}</>}
</Mutation>
2019-06-19 14:40:52 +00:00
);
};
}