I'm trying to display a new item each time a button is pressed. What I'm able to get right now is for state to update the same item depending on what button is pressed, but it's not generating a new item.
import React, { useState } from "react";
function Menu() {
const [menuItem, setMenuItem] = useState("");
const [menuList, setMenuList] = useState([]);
function addNewItem(e) {
e.preventDefault();
const newItem = [
"Spaghetti",
"Alfredo",
"Lasagna",
"Tortellini",
"Shrimp Scampi",
"Pizza",
];
setMenuList([...menuList].concat(newItem));
setMenuItem(e.target.value);
}
return (
<div>
<button onClick={addNewItem} value="Spaghetti">
Spaghetti
</button>
<button onClick={addNewItem} value="Alfredo">
Alfredo
</button>
<button onClick={addNewItem} value="Lasagna">
Lasagna
</button>
<button onClick={addNewItem} value="Tortellini">
Tortellini
</button>
<button onClick={addNewItem} value="Shrimp Scampi">
Shrimp Scampi
</button>
<button onClick={addNewItem} value="Pizza">
Pizza
</button>
<div>{menuItem}</div>
</div>
);
}
export default Menu;
CodePudding user response:
the way the addNewItem works currently is that it adds an array of all Items each time a button is clicked, instead it should only add the new item which the food name.
convert your addNewItem function to this and it should work
function addNewItem(e) {
e.preventDefault();
const newItem = e.target.value;
setMenuList(prevList => [...prevList, newItem]);
setMenuItem(newItem);
}
To Also display all the items in the array do this
return (
<div>
<button onClick={addNewItem} value="Spaghetti">
Spaghetti
</button>
<button onClick={addNewItem} value="Alfredo">
Alfredo
</button>
<button onClick={addNewItem} value="Lasagna">
Lasagna
</button>
<button onClick={addNewItem} value="Tortellini">
Tortellini
</button>
<button onClick={addNewItem} value="Shrimp Scampi">
Shrimp Scampi
</button>
<button onClick={addNewItem} value="Pizza">
Pizza
</button>
{
menuList.map((item) => {
return <div>{item}</div>
})
}
</div>
);
CodePudding user response:
Actually spreading the array makes it only add unique items to the array. if you want to merge two arrays including duplicates just concat without spreading.
setMenuList([...menuList].concat(newItems)); //duplicates in the second array doesnot get added
setMenuList([...menuList, ...newItems]); //shorter version of above
setMenuList(menuList.concat(newItems)); // merge two arrays as it is
setMenuList([...(m.concat(newItems))])