I have this array.map() arrow function and have the following error: "Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return"
Here is my code:
{productList.map((val) => {
const category = val.CategoryName;
// const quantity = val.ProductQuantity
if (category === "MotorcycleParts") {
if (val.ProductQuantity !== 0) {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
}
}
})}
I have read about the error and I see it has something to do with requiring a returning value, but I do have this?
A code example with a fix would help, I think it would be something simple.
CodePudding user response:
map
has to return a value for each item.
If you want to do some filtering, you should consider using Array.prototype.filter()
before, so you can remove the if
s in your map.
The code is also way more easy to read.
{productList.filter(val => val.CategoryName === "MotorcycleParts" && val.ProductQuantity !== 0)
.map((val) => {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
})}
CodePudding user response:
You could just return null when the listed conditions are not matched:
{productList.map((val) => {
const category = val.CategoryName;
// const quantity = val.ProductQuantity
if (category === "MotorcycleParts") {
if (val.ProductQuantity !== 0) {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
}
return null;
}
})}