1

I have a series of nested objects stored in state, I am trying to update the email / sms data fields. This working quite well.

The question I have is this, is there a better way in which to code the "onChange" handler?

Nested object

  const [settings, setSettings] = useState({
    notifications: {
      contact: {
        email: true,
        sms: false
      },
      updates: {
        email: true,
        sms: true
      }
    }
  });

Checkbox onChange handler function

  const onCheckBoxChanged = (e, settingType, settingSubType, checked) => {
    setSettings(prevState => {
      const updated = { ...prevState };
      updated.notifications[settingType][settingSubType] = checked;
      return updated;
    });
  };

The checkbox is part of semantic-ui-react.

<Checkbox checked={settings.notifications.contact.email} 
  onChange={(e, { checked }) => onCheckBoxChanged(e, "contact", "email", checked)} />

A working example can be found here codesandbox.io

Thanks

chrisbarm
  • 13
  • 2

1 Answers1

0

I have done cuple of small optimisations.

See CodeSandBox

The alternative method to updating your state would be:

Updating Multidimensional Array

I think using a temp variable for this usecase is acceptable.

hawx
  • 1,629
  • 5
  • 21
  • 37