When I set setItemPressed({[itemid]: false, ...itemPressed}), the itemid doesn't change to false, but when I setItemPressed({[itemid]: false}) itemid cahnges to false, but all of the other ids get removed. How do I make it so the other ids stay and this one changes?
const [itemPressed, setItemPressed] = useState({});
const changeColor = (itemid) => {
if(itemPressed.hasOwnProperty(itemid)){
setItemPressed({[itemid]: false, ...itemPressed})
}
else{
setItemPressed({...itemPressed, [itemid]: true});
}}
CodePudding user response:
The ordering matters.
setItemPressed({[itemid]: false, ...itemPressed})
should be flipped:
setItemPressed({...itemPressed, [itemid]: false})
Whatever comes later overrides what came before.
Edit: The reason why the press doesn't work is because the key is always in the object. Setting it to false doesn't delete it, so hasOwnProperty
will always return true after the first time it's pressed, and it'll always be set to false.
Here's how you should rewrite it to delete the key when it's unpressed:
const [itemPressed, setItemPressed] = useState({});
const changeColor = (itemid) => {
// Create a copy of the state
const newItemPressed = {...itemPressed};
if(newItemPressed.hasOwnProperty(itemid)){
// Delete the key from the object, this way you don't have unnecessary
// keys still in there.
delete newItemPressed[itemid];
}
else{
newItemPressed[itemid] = true;
}
setItemPressed(newItemPressed);
}
CodePudding user response:
Can you try to change the order of putting ...itemPressed and your property
const [itemPressed, setItemPressed] = useState({});
const changeColor = (itemid) => {
if(itemPressed.hasOwnProperty(itemid)){
setItemPressed({...itemPressed,[itemid]: false,})
}
else{
setItemPressed({...itemPressed, [itemid]: true});
}}