0

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);
};

2 Answers 2

2
const addCustomizationOption = (co) => {
    setTempRecipe({
                   ...tempRecipe,
                   customizationOptions:[...tempRecipe.customizationOptions,co]
                  });
};


const removeCustomizationOption = (co) => {
    setTempRecipe({
                   ...tempRecipe,
                   customizationOptions:tempRecipe.customizationOptions.filter(i => i.id !== co.id)
                  });
};
Sign up to request clarification or add additional context in comments.

1 Comment

take care that customizationOptions array must be instanciated before adding a customization option or it will crash. @AminNoura
1

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.

3 Comments

It's wrong, tempRecipe is an object with props, not an array
needed to push into tmpR.customizationOptions
Yep, fixed it now. My mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.