Home > database >  How to reset all objects specific value in react?
How to reset all objects specific value in react?

Time:04-08

I have the following useState:

  const [markedDates, setMarkedDates] = useState({
   "2022-04-05": {
     "selected": false,
   },
   "2022-04-08": {
     "selected": false,
   }
  });

Goal

My goal is to toggle the following to true or false.

enter image description here

But, only one object can be set as true, and this is where I am struggling to think of a correct method using React to achieve such logic.

As an example, I want to set 2022-04-05.selected to true:

  const [markedDates, setMarkedDates] = useState({
   "2022-04-05": {
     "selected": true, ######### SET AS TRUE #########
   },
   "2022-04-08": {
     "selected": false,
   }
  });

Now I want to set 2022-04-08.selected as true:

  const [markedDates, setMarkedDates] = useState({
   "2022-04-05": {
     "selected": false, ######### SET BACK TO FALSE #########
   },
   "2022-04-08": {
     "selected": true, ######### SET TO TRUE #########
   }
  });

Question

What would be the correct method to achieve such logic?

What I have tried

I came up with the following solution, but I am not sure if this is the correct way of re-setting all objects properties (selected = false) in react.

  const reset = () => {
    let resetMarkedDates = markedDates;
    for (const date in resetMarkedDates) {
      resetMarkedDates[date].selected = false;
    }
    setMarkedDates(resetMarkedDates);
  };

  const onDayPress = (day) => {
    reset();
    setMarkedDates((prevState) => ({
      ...prevState,
      [day]: { selected: true },
    }));
  };

CodePudding user response:

You can use a global variable instead of putting it directly in the useState parameter to be able to reset the initial state each time onDayPress is called. Note that, in your logic, since the previous state is the initial one, there's no need to pass a function to setState parameter if you aim to reset all the selected except one.

const initialState = {
  "2022-04-05": {
     "selected": false,
   },
   "2022-04-08": {
     "selected": false,
   }
}

const [markedDates, setMarkedDates] = useState(initialState);

const onDayPress = (day) => {
    setMarkedDates({
       ...initialState,
       [day]: { selected: true } 
      });
};

  • Related