I am trying to get the total from objects (product, sellingPrice) that renders dynamically on the screen after they have been entered through a form. I am using the map() function to loop through the list of entered data and using the reduce() function to get the sum total and display them on the screen, I think I am having issues with the reduce function as it shows NaN and Undefined in the console: I will gladly appreciate your help, thanks. Here are the useStates.
const [productName, setProductName] = useState("");
const [sellingPrice, setSellingPrice] = useState(0);
const [newItems, setNewItems] = useState([])```
//Here is then code
const displayAddedItemList = () => {
if (!visible) {
return (
<div>
<div>Items</div>
{newItems.map((items)=>{
const {productName,sellingPrice} = items;
return(
<>
<div className='itemsAdded'>
<div className='eachItemAdded'>
<div>{productName}</div>
<div>{sellingPrice}</div>
</div>
<div className='deleteEditFont'>
<FontAwesomeIcon icon={faTrashCan} />
</div>
</div>
</>
);
}).reduce(function(a,b) {
return
<div className='totalItemsAdded'>
<p>Total</p>
<p>${a + b.sellingPrice}</p>
</div>;
})
}
</div>
);
}
}
2
Answers
There is a small issue with the placement of the
return
statement within thereduce
function.the problem is
that the reduce function was placed inside the map function, which resulted in unexpected behavior. When you used return within the reduce function, it caused the map function to return undefined, and that’s why you were getting NaN or undefined.