Reputation: 863
I don't speak English very well but i will try it.
I have been looking for this for some time and i could not find a clear solution, I'm using React Hook for make a e-commerce and in my global store a have a list products that are in my cart.
I need count products for show total quantity, how i can run ".reduce" of my products list?
¿Is necesary create a useState?
Products list of my cart, it have this schema
[{
id: 5,
quantity: 3
},{
id: 23,
quantity: 1
}]
I have thought of doing it in the following ways
OPTION 1: (without useState, it's valid?)
import React from 'react';
import { useSelector } from 'react-redux';
const Cart = () => {
const cart = useSelector((state) => state.myCart); // list cart
const count = cart.reduce((total, product) => {
return total + product.quantity;
}, 0);
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
OPTION 2: This option has a little delay when show count
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
const Cart = () => {
const cart = useSelector((state) => state.myCart); // list cart
const [count, setCount] = useState(0)
useEffect(() => {
setCount(cart.reduce((total, product) => {
return total + product.quantity;
}, 0));
}, [cart])
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
what is the best way to do this ?
Thanks.
Upvotes: 0
Views: 571
Reputation: 203572
If you are only displaying the count you can also move the reduction into the selector function callback. Selectors allow you to return state however a component consumes it.
import React from "react";
import { useSelector } from "react-redux";
const cartCountSelector = state =>
state.myCart.reduce((total, product) => {
return total + product.quantity;
}, 0);
const Cart = () => {
const count = useSelector(cartCountSelector); // list cart count
return (
<div>
<span>{count}</span>
</div>
);
};
export default Cart;
Upvotes: 2