Home > Enterprise >  How to update the previous properties of state after onClick event?
How to update the previous properties of state after onClick event?

Time:11-29

So I want to update the previous properties of my state with array of objects.Initially I made only two objects.I want to implement bookmark functionality in my moviedb app.When I click on the icon it should change color as well as change the value of isFavorited property in my useState.

const [isActive, setActive] = useState({
        favorited: false,
        customColor: "white"
    });


const handleToggle = () => {
    setActive({ ...isActive, !favorited});
    if(isActive.favorited){
        setActive( {...isActive, customColor: "red"});
    }else{
        setActive( {...isActive, customColor: "white"});
    }
}

I am calling the handleToggle function on clicking a icon.How to make it so that the value of favorited toggles everytime I click it using useState?I get a error squiggle on !favorited

CodePudding user response:

Writing {...isActive, !favorited} is not a valid JS syntax.

Try rewriting the function to:

const handleToggle = () => {
  setActive((prevState) => {
    return {
      ...prevState,
      favorited: !prevState.favorited,
      customColor: prevState.favorited ? "red" : "white",
    };
  });
};

CodePudding user response:

You should update the state by using the prevState :-

 setActive((prevState) => ({
       ...prevState, favorited : !favorited}
    ));
  • Related