|
1 | | -import React from 'react'; |
| 1 | +import React, { useEffect } from 'react'; |
2 | 2 | import { connect, ConnectedProps } from 'react-redux'; |
3 | 3 | import { Form, Input, Button, Select } from 'antd'; |
4 | 4 | import { PhoneBrand } from 'src/constants/products'; |
5 | | -import { useHistory } from 'react-router-dom'; |
| 5 | +import { useHistory, useParams } from 'react-router-dom'; |
6 | 6 |
|
7 | | -import { createProduct } from './Product.thunks'; |
| 7 | +import { createProduct, editProduct, updateProduct } from './Product.thunks'; |
8 | 8 | import { PATH } from 'src/constants/paths'; |
9 | 9 | const { Option } = Select; |
10 | 10 |
|
11 | 11 | const mapStateToProps = (state: AppState) => ({ |
12 | 12 | products: state.products.products, |
| 13 | + product: state.products.product, |
13 | 14 | }); |
14 | | -const mapDispatchToProps = { createProduct }; |
| 15 | +const mapDispatchToProps = { createProduct, editProduct, updateProduct }; |
15 | 16 | const connector = connect(mapStateToProps, mapDispatchToProps); |
16 | | -interface Props extends ConnectedProps<typeof connector> {} |
17 | | - |
| 17 | +interface Props extends ConnectedProps<typeof connector> { |
| 18 | + edit: boolean; |
| 19 | +} |
18 | 20 | export const _ProductForm = (props: Props) => { |
19 | | - const { createProduct } = props; |
| 21 | + const { createProduct, edit, product, updateProduct, editProduct } = props; |
20 | 22 | const history = useHistory(); |
| 23 | + const params: ProductUrlParams = useParams(); |
21 | 24 | const layout = { |
22 | 25 | labelCol: { span: 4 }, |
23 | 26 | wrapperCol: { span: 16 }, |
24 | 27 | }; |
25 | 28 |
|
26 | 29 | const onFinish = values => { |
27 | | - createProduct(values); |
| 30 | + if (!edit) { |
| 31 | + createProduct(values); |
| 32 | + } |
| 33 | + |
28 | 34 | history.push(PATH.HOME); |
29 | 35 | }; |
30 | 36 |
|
31 | 37 | const allBrands = Object.values(PhoneBrand).filter( |
32 | 38 | x => typeof x !== 'number', |
33 | 39 | ); |
| 40 | + const initialValues = { ...product }; |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (edit) { |
| 44 | + const { id } = params; |
| 45 | + editProduct(id); |
| 46 | + } |
| 47 | + }, [edit, editProduct, params]); |
34 | 48 |
|
35 | 49 | return ( |
36 | 50 | <div className="main-body-section"> |
37 | 51 | <div id="main-contact" className="block"> |
38 | 52 | <div className="container"> |
39 | 53 | <div className="block-title"> |
40 | | - <h2>Create product</h2> |
| 54 | + <h2>{edit ? 'Create product' : 'Update product'}</h2> |
41 | 55 | </div> |
42 | 56 | <Form |
43 | 57 | {...layout} |
44 | 58 | name="product_form" |
45 | 59 | className="product-form" |
46 | | - initialValues={{ remember: true }} |
| 60 | + initialValues={{ ...initialValues, remember: true }} |
47 | 61 | onFinish={onFinish} |
48 | 62 | > |
49 | 63 | <Form.Item |
|
0 commit comments