Right now, this doesn't work.
const item = {name: "mike", apples: 20}
const [list, setList] = useState([{name: "peter", apples: 30}, {name: "mike", apples: 39}])
setList(list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))
I am able to get it working with the code below. I know it's not clean and that's why I'm trying to get the top code working the react way: using es6 within useState hook.
let newList = [...list]
let changed = false
newList.map(entry => {
if(entry.name == item.name) {
entry.apples = item.apples+entry.apples
}
if(changed) {
setList(newList)
}
Edit: I've also tried functional update on the state like below
setList(list => list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))
Here's the right way:
setList((previousList) =>
previousList.map((entry) =>
entry.name == item.name
? { ...entry, apples: entry.apples + item.apples }
: entry
)
);
entry.name == item.name ? entry.apples = item.apples+entry.apples
will not work because entry.apples = item.apples+entry.apples returns apples, but each element of the array should remain an object and you should also make sure that the state is not mutated (entry.apples = ... is bad because entry is mutated)