3

I want to use React.useReducer to update state. My state is an array of objects. When update action is triggered, not only value from desired index is updated but all of them. I want to have updated only the value from indicated array index. How can I do that?

After I click button1, I want to get

[{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false}]

instead of

[{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false}]

I tried to copy state as const newState = [...state] and use lodash's cloneDeep. Below, link to jsfiddle with code to reproduce.

https://jsfiddle.net/wtj5eyfh/

1 Answer 1

1

Your initial state of ingredientsState has references to the same object called initialIngredient. That caused everything to update when one entry was updated. Even though const stateToUpdate = [...state]; created a new array again all entries refers to the same object.

Fix

Change the following referenced array entries

const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    initialIngredient,
    initialIngredient,
    initialIngredient,
    initialIngredient
]);

To be an array of copies of initialIngredient object (spread operator simply create clones of the referred object)

const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient },
    { ...initialIngredient }
]);

JS Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

@Zaharskyy, check this out !!
Indeed, it works. Thank you :)

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.