I am trying to convert a class component to functional component but i keep getting problem, I think im doing it wrongly
Class Component:
JavaScript
x
31
31
1
class CountC extends React.Component {
2
3
componentDidMount() {
4
this.props.refreshCart();
5
}
6
7
render(){
8
const { cart } = this.props;
9
10
return (
11
<p> {`${cart !== null ? cart.order_items.length : 0}`}</p>
12
);
13
}};
14
15
const mapStateToProps = state => {
16
return {
17
18
cart: state.cart.shoppingCart,
19
};
20
};
21
22
23
const mapDispatchToProps = dispatch => {
24
return {
25
refreshCart: () => dispatch(fetchCart()),
26
27
}
28
}
29
30
export default connect(mapStateToProps, mapDispatchToProps)(CountC);
31
This is what i try to do as my Functional Component (Please note I dont understand function component just yet)
JavaScript
1
27
27
1
function CountC(props) {
2
const [refreshCart, setRefreshCart] = useState();
3
4
useEffect(() => {
5
setRefreshCart(true);
6
console.log("component mounted!");
7
}, []);
8
9
return ( <p> {`${cart !== null ? cart.order_items.length : 0}`}</p> );
10
11
const mapStateToProps = state => {
12
return {
13
14
cart: state.cart.shoppingCart,
15
};
16
};
17
18
19
const mapDispatchToProps = dispatch => {
20
return {
21
refreshCart: () => dispatch(fetchCart()),
22
23
}
24
}
25
26
export default connect(mapStateToProps, mapDispatchToProps)(CountC);
27
Its not giving me the desired output, I have tried tweaking it, still!,
Advertisement
Answer
Try this one, please.
JavaScript
1
11
11
1
const CountC = () => {
2
const dispatch = useDispatch();
3
const cart = useSelector((state) => state.cart.shoppingCart);
4
5
useEffect(() => {
6
dispatch(refreshCart());
7
}, [dispatch]);
8
9
return <p> {`${cart !== null ? cart.order_items.length : 0}`}</p>;
10
}
11