Update state in useState with object as input in function component

Viewed 12

Function component is used here

export default function Account() {

defining const with inputs as objects

const [state, setState] = useState({
  profile: true,
  orders: false,
  returns: false,
  coupon: false,
  referrals: false,
  rewards: false,
  redeem: false,
  address: false,
});

function to update state. I want to update state with setting all values in object to false and update specified key that is passes by onClick

function activeHandler(key) {
  setState((prevState) => {
    Object.keys(prevState).forEach((key) => {
      if (key == res) {
        prevState[key] = true;
      } else {
        prevState[key] = false;
      }
    });
    console.log(state);
    return prevState;
  });
}

JSX element, here onClick is used to pass key to function which is used to update state

return (
  <>
    <li
      className={
        state.profile
          ? "py-3 px-3 border-bottom active"
          : "py-3 px-3 border-bottom"
      }
      onClick={() => activeHandler("profile")}
    >
      Profile
    </li>
    <li
      className={
        state.orders
          ? "py-3 px-3 border-bottom active"
          : "py-3 px-3 border-bottom"
      }
      onClick={() => activeHandler("orders")}
    >
      Orders
    </li>
  </>
);
1 Answers

You don't say there is any issue or ask for help with anything, but it's clear your activeHandler callback function is simply mutating state so I'll assume that's the issue you are asking for help with. The returned state necessarily needs to be a new object reference. Shallow copy any state and nested state that is being updated.

Example:

function activeHandler(key) {
  setState((prevState) => ({
    ...prevState,           // <-- shallow copy previous state
    [key]: !prevState[key], // <-- toggle value by key
  }));
}
Related