Reputation: 317
I have a little problem understanding something. So I need your help to do an example for me. Please kindly write this two functions with a better solution.
the setTempRecipe is a coming from useState hook in my react functional component.
const addCustomizationOption = (co) => {
const tmpR = Object.assign({}, tempRecipe);
tmpR.customizationOptions.push(co);
setTempRecipe(tmpR);
};
and the second one is:
const removeCustomizationOption = (co) => {
const tmpR = Object.assign({}, tempRecipe);
const g = tmpR.customizationOptions.findIndex(item => item.id === co.id);
tmpR.customizationOptions.splice(g, 1);
setTempRecipe(tmpR);
};
Upvotes: 0
Views: 66
Reputation: 5937
You have the right idea, you shouldn't mutate state variables, instead take a deep copy and apply new values. What I would go for is:
const addCustomizationOption = (co) => {
setTempRecipe(tr => ({...tr, customizationOptions: [...tr.customizationOptions,co]}));
};
This spread operator will add co
to the tempRecipe array and tr
refers to the current state.
And, for the second one, you can filter the array:
const removeCustomizationOption = (co) => {
setTempRecipe(tr => ({...tr, customizationOptions: tr.customizationOptions.filter(recipe => recipe.id !== co.id))})
};
Since .filter()
function returns a new array, you can directly filter out the id and set the new filtered array.
Upvotes: 1
Reputation: 5831
const addCustomizationOption = (co) => {
setTempRecipe({
...tempRecipe,
customizationOptions:[...tempRecipe.customizationOptions,co]
});
};
const removeCustomizationOption = (co) => {
setTempRecipe({
...tempRecipe,
customizationOptions:tempRecipe.customizationOptions.filter(i => i.id !== co.id)
});
};
Upvotes: 2