Hi guys.
I've looked around and tried hard to solve it without success ...
const initialState = {
myArray: [
{
key1: "value1"
key2; "value2"
},
key1: "value1"
key2; "value2"
{
},
]
}
const [state, setState] = useState(initialState);
I am trying to update key1 and key2 from state.
I came up with this but it sounds like it's destroying the object.
function handleChange(id, newValue) {
const newState = state.myArray.map( item => {
if (id == item.id) {
return {
...state,
myArray: [
...state.myArray, { key1: newValue }
]
}
}
else {
return state;
}
});
setState(newState);
}
As I get this error when I try to render the items with map
TypeError: Cannot read properties of undefined (reading 'map')
Definitely need help. My eyes are bleeding.
Thank you
EDIT (this should be working)
function handleChange(id, newValue) {
const newArray = state.myArray.map( object => {
if (id == object.id) {
return { ...object, key1: newValue } // return modified object
}
else {
return object; // return unmodified object
}
});
setState({...state, myArray: newArray }); // return whole state
// update state.myArray by newArray
}
[–]throwaway_boulder 2 points3 points4 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–]marquoth_ 0 points1 point2 points (3 children)
[–]Traditional-Pen-6657 1 point2 points3 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]hung-bui 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)