'REACT: Warning: Received NaN for the `children` attribute. If this is expected, cast the value to a string
I need to use a quantity for my cart, I'm learning react, but I get this warning: Warning: Received NaN for the children attribute. If this is expected, cast the value to a string.
import { createContext, useState, useContext, useEffect } from "react";
export const CartContext = createContext([]);
export const CartProvider = ({children}) => {
const [cart, setCart] = useState([]);
//const cantidadProductos = cart.length;
const [cartQuantity, setCartQuantity] = useState(0);
useEffect(() => {
const getQuantity = () => {
let cantidadTotalProductos = 0;
cart.forEach((orden)=>{
cantidadTotalProductos += Number(orden.cantidadTotalProductos);
});
setCartQuantity(cantidadTotalProductos);
}
getQuantity();
}, [cart]);
const addItem = (item, cantidad) => {
const newItem = { item, cantidad };
const itemEsta = cart.find((order) => order.item.id === item.id);
if(itemEsta){
const actualizarCarrito = cart.map((order) => {
if(order.item.id === item.id){
return {...order, cantidad: cantidad + order.cantidad};
}else{
return order;
}
});
setCart(actualizarCarrito);
}else{
setCart((prevState) => [...prevState, newItem]);
}
};
const removeItem = (id) => {
setCart((prev) => prev.filter((element) => element.item.id !== id));
};
const clearAll = () => {
setCart([]);
};
return (
<CartContext.Provider value={{ cart, addItem, removeItem, clearAll, cartQuantity }}>
{children}
</CartContext.Provider>
);
};
export const useCart = () => useContext(CartContext);
And then in the component:
import './Carrito.css';
import { useCart } from "../context/CartContext";
function Carrito () {
const { cartQuantity } = useCart();
return <div className="editarCarrito">
<p className="carritoCantidad">{ cartQuantity }</p>
</div>
}
export default Carrito;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
