saleor-dashboard/src/mutations.tsx

49 lines
1.4 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-06-19 14:40:52 +00:00
import useNotifier from "./hooks/useNotifier";
import i18n from "./i18n";
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-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}
onError={err => {
const msg = i18n.t("Something went wrong: {{ message }}", {
message: err.message
});
notify({ text: msg });
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
);
};
}