I have the following react state, I want to update the second value not the whole object and I don't want to use an object as a value either, for now I can only change the whole object but not the specific wanted value how to target and update the wanted index.
// State
const [state, setState] = useState({
element: [false, 'starter text']
});
// Update State logic
setState({ ...state, element: [(element[1] = 'updated text')] });
When updating state in React you shallow copy the state, and nested state, that you are updating. For arrays this means you shallow copy the array.
// State
const [state, setState] = useState({
element: [false, 'starter text']
});
// Update State logic
setState(state => ({
// shallow copy any previous root-level state
...state,
// shallow copy the previous state's element array
// when the mapped index matches the index you want to update
// return the updated value, otherwise return existing value
element: state.element.map((el, i) => i === 1 ? 'updated text' : el)
}));
If the array was an array of objects then you need to shallow copy them as well, then update the nested property.
Example:
element: state.element.map(
(el, i) => i === 1
? {
...el,
nestedProperty: 'updated text'
}
: el
)
I know this Immutable Update Patterns doc is from Redux, but is solves many common React state update issues.
You can create a new state state as codeSandbox
setState(oldState => {
const newState = { ...oldState, element: [ ...oldState.element ]};
newState.element[1] = "updated text";
return newState;
})
You can use Object.assign. Since an array is an Object with indices as its properties, you can do this:
const arr = [1, 2, 3, 4, 5];
const updatedArr = Object.assign([], arr, { 1: 10 }); // Update value at index 1.
console.log(arr);
console.log(updatedArr);