mercredi 15 avril 2020

React checkbox group is not being updated with the state

Hi I an using this state for the checkbox group

  const [ socialLists, setSocialList ] = useState([]);

  useEffect(() => {
    setSocialList([
      { name: 'Facebook', checked: true },
      { name: 'Twitter', checked: true },
      { name: 'Instagram', checked: true }
    ]);

  }, []);

The checkbox is initially checked, I am updating the state with an onChange function on my checkboxes, but it the checked value is not being updated. This is my jsx

<FormGroup row>
              {socialLists.map((social) => (
                <FormControlLabel
                  key={social.name}
                  control={
                    <CustomCheckbox value={social.name} checked={social.checked} onChange={filterScheduleData} />
                  }
                  label={social.name}
                />
              ))}
            </FormGroup>

This is the onChange function

  const filterScheduleData = (event, checked) => {
    const checkboxes = socialLists;
    checkboxes.forEach((i) => {
      if (i.name === event.target.value) {
        i.checked = checked;
      }
    });
    setSocialList(checkboxes);
  };

In the end the list is being updated but the checkbox value does not change with it




Aucun commentaire:

Enregistrer un commentaire