Skip to content
Advertisement

Change class component to functional component with props

I am trying to convert a class component to functional component but i keep getting problem, I think im doing it wrongly

Class Component:

class CountC extends React.Component {

    componentDidMount() {
        this.props.refreshCart();
      }

 render(){
        const { cart } = this.props;

        return (
           <p> {`${cart !== null ? cart.order_items.length : 0}`}</p>
);
}};

const mapStateToProps = state => {
    return {

      cart: state.cart.shoppingCart,
    };
  };


const mapDispatchToProps = dispatch => {
    return {
        refreshCart: () => dispatch(fetchCart()),

    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CountC);

This is what i try to do as my Functional Component (Please note I dont understand function component just yet)

function CountC(props) {
  const [refreshCart, setRefreshCart] = useState();
  
  useEffect(() => {
    setRefreshCart(true);
    console.log("component mounted!");
  }, []);

return ( <p> {`${cart !== null ? cart.order_items.length : 0}`}</p> );

 const mapStateToProps = state => {
        return {
    
          cart: state.cart.shoppingCart,
        };
      };
    
    
    const mapDispatchToProps = dispatch => {
        return {
            refreshCart: () => dispatch(fetchCart()),
    
        }
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(CountC);

Its not giving me the desired output, I have tried tweaking it, still!,

Advertisement

Answer

Try this one, please.

 const CountC = () => {
  const dispatch = useDispatch();
  const cart = useSelector((state) => state.cart.shoppingCart);

  useEffect(() => {
    dispatch(refreshCart());
  }, [dispatch]);

  return <p> {`${cart !== null ? cart.order_items.length : 0}`}</p>;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement