-
-
Save alexesDev/68be460a1edeca65d6049cf804db898e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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