useReducer array of objects
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
function MyReducer () {
const initialIngredient = {
amount: null,
kcal: null,
name: null,
isPieceType: false,
};
const mealReducer = (
state,
action,
) => {
const {type, index} = action;
switch (type) {
case 'UPDATE':
if (!index && index !== 0) {
return state;
}
const {value, ingredientProp} = action;
if (!value || !ingredientProp) {
return state;
}
const stateToUpdate = [...state];
console.log(stateToUpdate)
// invalid update
switch (ingredientProp) {
case 'amount':
stateToUpdate[index].amount = value;
return stateToUpdate;
case 'kcal':
// try Lodash
if (value === 333) {
console.log('Lodash deepcopy')
let lodashState = _.cloneDeep(state);
lodashState[index].kcal = value;
return lodashState;
}
console.log('UPDATE KCAL')
stateToUpdate[index].kcal = value;
return stateToUpdate;
case 'name':
stateToUpdate[index].name = value;
return stateToUpdate;
}
return state;
default:
throw new Error();
}
};
const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
{...initialIngredient}, {...initialIngredient}, {...initialIngredient}, {...initialIngredient},
]);
const handleButton1click = () => {
ingredientsDispatch({
type: 'UPDATE',
index: 2,
value: 125,
ingredientProp: 'kcal',
})
}
const handleButton2click = () => {
ingredientsDispatch({
type: 'UPDATE',
index: 1,
value: 750,
ingredientProp: 'kcal',
})
}
const handleButton3click = () => {
ingredientsDispatch({
type: 'UPDATE',
index: 3,
value: 333,
ingredientProp: 'kcal',
})
}
return (
<div...