Home > Mobile >  Get Price From Every Child Component And do Sum In Parent Component
Get Price From Every Child Component And do Sum In Parent Component

Time:07-23

i am creating an ecommerce site. i am having a problem in the cart. in the cart I fetch all cart item and then map the result. i have created a child component for every cart item. every child component show the item price. i want to access the price of every child element in parent component and set them all into an array.

here is the parent component

    const Cart = () => {
  const [total, setTotal] = useState([]);

  const { products } = useSelector((state) => state.allProducts);
  const cart = getStoredCart();
  const cartItems = products?.filter(({_id}) => cart.some(x => x.id === _id))

  return (
        <div className="mt-4">
          {cartItems?.length > 0 && (
            <>
              <div >
                <table >
                  <thead className="">
                    <tr className="text-center">
                      <th className="text-left">Product Details</th>
                      <th className="">Quantity</th>
                      <th className="">Price</th>
                    </tr>
                  </thead>
                  <tbody>
                    {cartItems?.map((item, index) => (
                      <TableRow key={item._id} item={item} index={index}/>
                    ))}
                  </tbody>
                </table>
            </>
          )}
        </div>
  );
};

child component

    const TableRow = ({ item }) => {

    const [quantity, setQuantity] = useState(1);
  let price = Number((Number(quantity) * Number(item.price)).toFixed(2));
// I want this price value will set to the total as an array element

  const handlePrice = (props) => {
    if (props === 0) {
      setQuantity((prevQ) => prevQ   1);
    }

    if (props === 1) {
      if (quantity > 1) {
        setQuantity((prevQ) => prevQ - 1);
      } else {
        return;
      }
    }
  };

  return (
    <tr>
      <td className="">
        <div className="flex space-x-2 items-center justify-center">
          <button onClick={() => handlePrice(1)} className="text-xl font-bold">
            <HiMinus />
          </button>
          <div className="w-16 h-10 border-2 rounded">
            <input
              className="w-full h-full text-center outline-none font-medium"
              type="number"
              value={quantity}
              onChange={(e) => setQuantity(Number(e.target.value))}
              name=""
              id=""
            />
          </div>
          <button onClick={() => handlePrice(0)} className="text-xl font-bold">
            <HiPlus />
          </button>
        </div>
      </td>
      <td className="w-40 text-center">{price}</td>
    </tr>
  );
};

CodePudding user response:

Parent

const [priceArr,setPriceArr]=useState([])
const getPrices=(price)=>{
    setPriceArr(oldArray => [...oldArray,price])
}
<TableRow key={item._id} item={item} index={index} getPrices={getPrices} />

from Children using props.getPrices(arguement for price) send it to parent

CodePudding user response:

thanks for help. but i found the solution.

i have created an empty object and take two state in the parent component.

  const allPrice = {};
  const [priceObj, setPriceObj] = useState({});
  const [total, setTotal] = useState(0);

and In the child component i have done this

  const { allPrice, setPriceObj } = useContext(CartContext);
  const [quantity, setQuantity] = useState(1);
  const price = Number((Number(quantity) * Number(item.price)).toFixed(2));
  allPrice[index] = price;

  const handlePrice = (props) => {
    if (props === 0) {
      setQuantity((prevQ) => prevQ   1);
    }
    if (props === 1) {
      if (quantity > 1) {
        setQuantity((prevQ) => prevQ - 1);
      } else {
        return;
      }
    }
    setPriceObj(allPrice);
  };

NB: i have used context API; i don't know it is a good code or not. if anyone know better solution hope you will submit here.

  • Related