Qn regarding 2nd challenge of https://beta.reactjs.org/learn/choosing-the-state-structure
My code for updating "pack" doesnt work when using ternary operator. But when I use normal if else statements, it works:
ternary operator:
const packed = items.reduce((acum, cur, i) => {
console.log(`Index: ${i}, packed: ${cur.packed}, Before:${acum}, Addition: ${cur.packed ? 1 : 0}`);
return acum + cur.packed ? 1 : 0;
}, 0);
If else version:
const packed = items.reduce((acum, cur) => {
if (cur.packed) return acum + 1
else return acum;
}, 0);
console.log(packed);
Full code (official suggested ans, my ans is the same as this except the "pack" part)
import { useState } from 'react';
import AddItem from './AddItem.js';
import PackingList from './PackingList.js';
let nextId = 3;
const initialItems = [
{ id: 0, title: 'Warm socks', packed: true },
{ id: 1, title: 'Travel journal', packed: false },
{ id: 2, title: 'Watercolors', packed: false },
];
export default function TravelPlan() {
const [items, setItems] = useState(initialItems);
const total = items.length;
const packed = items
.filter(item => item.packed)
.length;
function handleAddItem(title) {
setItems([
...items,
{
id: nextId++,
title: title,
packed: false
}
]);
}
function handleChangeItem(nextItem) {
setItems(items.map(item => {
if (item.id === nextItem.id) {
return nextItem;
} else {
return item;
}
}));
}
function handleDeleteItem(itemId) {
setItems(
items.filter(item => item.id !== itemId)
);
}
return (
<>
<AddItem
onAddItem={handleAddItem}
/>
<PackingList
items={items}
onChangeItem={handleChangeItem}
onDeleteItem={handleDeleteItem}
/>
<hr />
<b>{packed} out of {total} packed!</b>
</>
);
}
Expected a "pack" to count the number of packed items, but always return 1 when using ternary operator, regardless of the initial value (i tried to set it to 1000 and it still returned 1)
>Solution :
This is the correct version using ternary
const packed = items.reduce((acum, cur, i) => {
console.log(`Index: ${i}, packed: ${cur.packed}, Before:${acum}, Addition: ${cur.packed ? 1 : 0}`);
return cur.packed ? acum + 1 : acum;
}, 0);