Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created April 10, 2020 11:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexesDev/68be460a1edeca65d6049cf804db898e to your computer and use it in GitHub Desktop.
Save alexesDev/68be460a1edeca65d6049cf804db898e to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { graphql, useQuery, useMutation } from 'relay-hooks';
import { Form, Input, Button } from 'antd';
import { productQuery } from './__generated__/productQuery.graphql';
import { productCreateMutation } from './__generated__/productCreateMutation.graphql';
import { productUpdateMutation } from './__generated__/productUpdateMutation.graphql';
const query = graphql`
query productQuery($rowId: BigInt!) {
data: productByRowId(rowId: $rowId) {
id
rowId
name
}
}
`;
const createMutation = graphql`
mutation productCreateMutation($input: CreateProductInput!) {
data: createProduct(input: $input) {
product {
id
rowId
name
}
}
}
`;
const updateMutation = graphql`
mutation productUpdateMutation($input: UpdateProductByRowIdInput!) {
data: updateProductByRowId(input: $input) {
product {
id
name
}
}
}
`;
export default ({ history, match }: { history: any, match: any }) => {
const isNew = match.params.rowId === 'new';
const { props, error } = useQuery<productQuery>(query, {
rowId: match.params.rowId,
}, {
skip: isNew,
});
const [createMutate, createMutationState] = useMutation<productCreateMutation>(createMutation);
const [updateMutate, updateMutationState] = useMutation<productUpdateMutation>(updateMutation);
const [form] = Form.useForm();
if (error) {
return <div>Error: {error.message}</div>;
}
if (!props && !isNew) {
return <div>Loading...</div>;
}
if (!isNew && !props?.data) {
return <div>Not found</div>;
}
const saving = updateMutationState.loading || createMutationState.loading;
const save = async (values: any) => {
if (isNew) {
const res = await createMutate({
variables: {
input: {
product: values,
},
},
});
const rowId = res.data?.product?.rowId;
if (rowId) {
history.push(`/products/${rowId}`);
}
} else {
updateMutate({
variables: {
input: {
rowId: match.params.rowId,
productPatch: values,
},
},
});
}
};
return (
<div>
<Form form={form} initialValues={props?.data || {}} onFinish={save}>
<Form.Item name="name" label="Name" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Button type="primary" htmlType="submit" loading={saving}>
Submit
</Button>
</Form>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment