I\'m working with a deeply nested state object in React. My code base dictates that we try to stick with function components and so every time I want to update a key/value pair
I think you should be using the functional form of setState
, so you can have access to the current state and update it.
Like:
setState((prevState) =>
//DO WHATEVER WITH THE CURRENT STATE AND RETURN A NEW ONE
return newState;
);
See if that helps:
function App() {
const [nestedState,setNestedState] = React.useState({
top_level_prop: [
{
nestedProp1: "nestVal1",
nestedProp2: "nestVal2",
nestedProp3: "nestVal3",
nestedProp4: [
{
deepNestProp1: "deepNestedVal1",
deepNestProp2: "deepNestedVal2"
}
]
}
]
});
return(
This is my nestedState:
{JSON.stringify(nestedState)}
);
}
ReactDOM.render( , document.getElementById('root'));
UPDATE: With dropdown
function App() {
const [nestedState,setNestedState] = React.useState({
propA: 'foo1',
propB: 'bar'
});
function changeSelect(event) {
const newValue = event.target.value;
setNestedState((prevState) => {
return({
...prevState,
propA: newValue
});
});
}
return(
My nested state:
{JSON.stringify(nestedState)}
);
}
ReactDOM.render( , document.getElementById('root'));