1
const [checkedHealth, setCheckedHealth] = useState(checkboxHealthLabels);

const handleChangeHealth = (event) => {
setCheckedHealth([
  ...checkedHealth,
  [event.target.name]: event.target.checked,
]);

};

and checkboxHealthLabels file :

export const checkboxHealthLabels = [
   { name: "Alcohol-Free", checked: false },
   { name: "Celery-Free", checked: false },
   { name: "Dairy-Free", checked: false },
];

now I want to change just one object for example : { name: "Alcohol-Free", checked: false }, and other values have to stay same. How can I do that?

buzatto
  • 9,704
  • 5
  • 24
  • 33
bizimsiti
  • 78
  • 6

1 Answers1

1

Find the index of the object in the array with the same name, then toggle it as needed:

const handleChangeHealth = ({ target }) => {
  const { name } = target;
  const index = checkedHealth.findIndex(obj => obj.name === name);
  setCheckedHealth([
    ...checkedHealth.slice(0, index),
    { name, checked: target.checked },
    ...checkedHealth.slice(index + 1)
  ]);
};

You could also consider having the state be an object (with the names being the object properties) instead of an array, it might be easier.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • this function is adding new object. `1: Object { name: "Alcohol-Free", checked: true } ​ 2: Object { name: "Alcohol-Free", checked: false } ​ 3: Object { name: "Celery-Free", checked: false } ​` – bizimsiti Feb 10 '21 at 23:04
  • Whoops, I typed `.find` instead of `.findIndex` – CertainPerformance Feb 10 '21 at 23:05
  • thanks a lot. Its working now. But ı have a new question :'( – bizimsiti Feb 10 '21 at 23:13
  • (Regarding your now-deleted comment) Yes, that's exactly the object structure I was thinking of. Only problem is, you need to wait for the component to re-render to see the updated state. See https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – CertainPerformance Feb 10 '21 at 23:17