Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested object state setting

I have a problem with setting the state. After clicking the button, the status of all checkboxes should be set according to the initiating state. Unfortunately, nothing happens. What am I doing wrong in setObject method?

Code source: https://codesandbox.io/s/competent-saha-6iwjw?file=/src/App.js

like image 883
jan.kowalski Avatar asked Apr 09 '26 20:04

jan.kowalski


1 Answers

There is no use of toggle in OwnToggle:

const OwnToggle = props => {
  // not `value`
  const { toggle, path, toggleSwitchHandler } = props;

  return (
    <Toggle checked={toggle} onChange={e => toggleSwitchHandler(path, e)} />
  );
};

And you don't pass the state object:

// not obj
<FirstRow toggle={object} toggleSwitchHandler={toggleSwitchHandler} />
<SecondRow toggle={object} toggleSwitchHandler={toggleSwitchHandler} />

Also, you mutating the global object in toggleSwitchHandler and then you relay on it:

  const toggleSwitchHandler = (path, e) => {
    // is a SHALLOW COPY, you need a deep copy here
    const tempObject = { ...obj };
    // mutate global object
    set(tempObject, path, e.target.checked);
    // relay on global object
    setObject({ ...object, ...tempObject });
  };

Edit trusting-visvesvaraya-rqo14

like image 58
Dennis Vash Avatar answered Apr 12 '26 10:04

Dennis Vash