I have several fields that are updating state. For that they will pass into function group key, key and new value. How can I update my state using passed variables?
This is what I tried:
const [state, setState] = useState({
firstGroup:{
apple: '',
cinnamon: '',
},
secondGroup:{
apple: '',
cinnamon: '',
},
})
const updateState = (groupKey, key, newValue) => {
const newState = {
...manualRange,
[groupKey][key]: value,
};
setState(newState);
};
As you can see I'm targeting either apple or cinnamon keys, which are located in either first or second group. So idea is to pass group and key into function, but I don't know how to update existing object with new values.
CodePudding user response:
const [firstGroup, setFistGroup] = useState({apple: '', cinnamon: ''};
const [secondGroup, setSecondGroup] = useState({apple: '', cinnamon: ''};
const updateState = (groupKey, key, newValue) => {
if(groupKey === 'first') {
setFirstGroup({...firstGroup, [key]: newValue});
else {
setSecondGroup({...secondGroup, [key]: newValue});
};
}
But for complex state it is recommended to use useReducer
https://en.reactjs.org/docs/hooks-reference.html#usereducer
CodePudding user response:
Try this for your updateState
function:
const updateState = (groupKey, key, newValue) => {
const newState = {
...manualRange,
[groupKey]: {
...manualRange[groupKey],
[key]: value,
},
};
setState(newState);
};
I'm assuming manualRange
is a reference to the existing state in this context. Otherwise, you probably want to use state
instead.