UNPKG

@tomino/dynamic-form-semantic-ui

Version:

Semantic UI form renderer based on dynamic form generation

106 lines 4.05 kB
import * as React from 'react'; import { Mutation } from 'react-apollo'; import gql from 'graphql-tag'; import { createComponents } from '../common'; import { observer } from 'mobx-react'; import { Context } from '../context'; import { parseParameter } from './apollo_query_view'; import { simpleHandle } from '../helpers'; import { Message } from 'semantic-ui-react'; export const ApolloMutation = observer((props) => { const [error, setError] = React.useState(null); const { owner, formElement: { props: { mutation, target, onError, onResult, clickHandler, variables, boundVariables, onSubmit, successAlert, errorAlert } } } = props; const context = React.useContext(Context); if (!mutation) { return React.createElement("div", null, "Please specify the mutation"); } let parsedMutation; try { parsedMutation = React.useMemo(() => gql([mutation]), [mutation]); } catch (ex) { return React.createElement("pre", null, "Mutation Error: ", ex.message); } return (React.createElement(Mutation, { mutation: parsedMutation, onCompleted: (data) => { if (target) { owner.setValue(target, data[Object.getOwnPropertyNames(data)[0]]); } if (onResult) { simpleHandle(props, onResult, context, data); } if (successAlert) { if (!context.alert) { throw new Error('You need to add AlertProvider'); } context.alert.success(successAlert); } if (error) { setError(null); } }, onError: (data) => { try { if (onError) { simpleHandle(props, onError, context, data); } if (errorAlert) { if (!context.alert) { throw new Error('You need to add AlertProvider'); } context.alert.error(errorAlert); } setError(data.message); } catch (ex) { setError(ex); } } }, (mutate, { loading, error, data }) => { let handlers = props.handlers; if (clickHandler) { const newClickHandler = () => { let currentVariables = onSubmit ? simpleHandle(props, onSubmit, context, data) : {}; if (currentVariables == null) { return; } if (variables) { for (let v of variables) { currentVariables[v.name] = parseParameter(v.value, v.type); } } if (boundVariables) { for (let v of boundVariables) { currentVariables[v.name] = owner.getValue(v.source); } } mutate({ variables: currentVariables }); }; handlers = { ...handlers, [clickHandler]: newClickHandler }; } const components = createComponents({ ...props, handlers, extra: { loading, error, data } }); if (error) { return (React.createElement(React.Fragment, null, React.createElement(Message, { color: "red", header: "Query Error", icon: "ban", content: error.message ? error.message.split(':')[error.message.split(':').length - 1] : JSON.stringify(error, null, 2) }), React.createElement("br", null), components)); } return React.createElement(React.Fragment, null, components); })); }); export const ApolloMutationView = { Component: ApolloMutation, toString: () => { throw new Error('Not Implemented'); } }; //# sourceMappingURL=apollo_mutation_view.js.map