1
1
import React , { useEffect , useState } from 'react' ;
2
2
import { useDispatch , useSelector } from 'react-redux' ;
3
- import { detailsProduct } from '../actions/productActions' ;
3
+ import { detailsProduct , updateProduct } from '../actions/productActions' ;
4
4
import LoadingBox from '../components/LoadingBox' ;
5
5
import MessageBox from '../components/MessageBox' ;
6
+ import { PRODUCT_UPDATE_RESET } from '../constants/productConstants' ;
6
7
7
8
export default function ProductEditScreen ( props ) {
8
9
const productId = props . match . params . id ;
@@ -16,9 +17,21 @@ export default function ProductEditScreen(props) {
16
17
17
18
const productDetails = useSelector ( ( state ) => state . productDetails ) ;
18
19
const { loading, error, product } = productDetails ;
20
+
21
+ const productUpdate = useSelector ( ( state ) => state . productUpdate ) ;
22
+ const {
23
+ loading : loadingUpdate ,
24
+ error : errorUpdate ,
25
+ success : successUpdate ,
26
+ } = productUpdate ;
27
+
19
28
const dispatch = useDispatch ( ) ;
20
29
useEffect ( ( ) => {
21
- if ( ! product || product . _id !== productId ) {
30
+ if ( successUpdate ) {
31
+ props . history . push ( '/productlist' ) ;
32
+ }
33
+ if ( ! product || product . _id !== productId || successUpdate ) {
34
+ dispatch ( { type : PRODUCT_UPDATE_RESET } ) ;
22
35
dispatch ( detailsProduct ( productId ) ) ;
23
36
} else {
24
37
setName ( product . name ) ;
@@ -29,17 +42,31 @@ export default function ProductEditScreen(props) {
29
42
setBrand ( product . brand ) ;
30
43
setDescription ( product . description ) ;
31
44
}
32
- } , [ product , dispatch , productId ] ) ;
45
+ } , [ product , dispatch , productId , successUpdate , props . history ] ) ;
33
46
const submitHandler = ( e ) => {
34
47
e . preventDefault ( ) ;
35
48
// TODO: dispatch update product
49
+ dispatch (
50
+ updateProduct ( {
51
+ _id : productId ,
52
+ name,
53
+ price,
54
+ image,
55
+ category,
56
+ brand,
57
+ countInStock,
58
+ description,
59
+ } )
60
+ ) ;
36
61
} ;
37
62
return (
38
63
< div >
39
64
< form className = "form" onSubmit = { submitHandler } >
40
65
< div >
41
66
< h1 > Edit Product { productId } </ h1 >
42
67
</ div >
68
+ { loadingUpdate && < LoadingBox > </ LoadingBox > }
69
+ { errorUpdate && < MessageBox variant = "danger" > { errorUpdate } </ MessageBox > }
43
70
{ loading ? (
44
71
< LoadingBox > </ LoadingBox >
45
72
) : error ? (
0 commit comments