I'm trying to set the 'keys' variable inside a set function.
The 'keys' variable will not pass as the key
How do I go about passing the variable keys as the key inside of this object?
const [user, setUser] = useState({
key: 'value',
key2: 'value2',
key3: 'value3'
})
const passwordChange = (keys, elem) => {
setUser({...user, keys: elem})
}
passwordChange(key3, 'new value')
CodePudding user response:
const [user, setUser] = useState({
key: 'value',
key2: 'value2',
key3: 'value3'
})
const passwordChange = (keys, elem) => {
setUser({...user, [keys]: elem})
}
passwordChange('key3', 'new value')
Try this.
CodePudding user response:
As you mentioned 'keys' inside object will consider as a string. So you need to modify function as below.
const passwordChange = (keys, elem) => {
let cUser = user;
cUser[keys] = elem;
setUser(cUser);
}
CodePudding user response:
You can take the previous value and update the key with new value
const passwordChange = (keys, elem) => {
setUser((prevState) => {
return {
...prevState,
[keys]: elem,
};
});
};