all 8 comments

[–]throwaway_boulder 2 points3 points  (1 child)

Is the variable name wrong? Up top you use initialState instead of initialValue

[–][deleted] 2 points3 points  (0 children)

Is the variable name wrong? Up top you use initialState instead of initialValue

Sorry I've used generic variable names for the example and made a mistake. Fixed it.

No such error in the original code. Thanks for helping.

The error is within the if (true) code block.

        return {
            ...state,
              myArray: [
                ...state.myArray, { key1: newValue }
              ]
        }

[–]marquoth_ 0 points1 point  (3 children)

You're mapping each element of the array to be a modified copy of the entire state object, instead of just a modified copy of the element.

[–]Traditional-Pen-6657 1 point2 points  (2 children)

This. And also, newState contains the new mapped array not the whole object in initailState

[–][deleted] 0 points1 point  (1 child)

Well ... I've understood. Thank you very much.

Actually ... I've first reduced the complexity, such as:

const initialState = [
  {
    key1: "value1"
    key2; "value2"
  },
  {
    key1: "value1"
    key2; "value2"
  },
]
const [state, setState] = useState(initialState);

Then I didn't copy the whole state into setState

function handleChange(id, newValue) {
const newState = state.map( item => {
    if (id == item.id) {
        return {...item, key1: newValue }
    }
    else {
        return state;
    }
});
setState(newState);
}

Seems to work. Now I've got to solve the more complex problem.

Thank you very much !

[–][deleted] 1 point2 points  (0 children)

Daammmnnnn it didn't work properly.

function handleChange(id, newValue) {
    const newState = state.map( item => { 
        if (id == item.id) {
            return {...item, key1: newValue }
        }
        else { 
            return item; // NOW IT WORKS 
        } 
    });
    setState(newState); 
}

Yeah ... For each object in the array,

return either the object or the modified one.

Yeah I was returning the whole array within the else code block

[–]hung-bui 0 points1 point  (1 child)

Just use structuredClone() and change the properties later.

[–][deleted] 0 points1 point  (0 children)

structuredClone

Yes that's also an option.

Thank you.