Nested object state setting

Viewed 61
3 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

You are passing a const instead of parent state

// obj is a const
<FirstRow toggle={obj} toggleSwitchHandler={toggleSwitchHandler} />
<SecondRow toggle={obj} toggleSwitchHandler={toggleSwitchHandler} />

Try to pass changing state

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

You are not using the toggle which reflects the checking status. but you used value, which is never set.

import React from "react";
import Toggle from "react-toggle";

const OwnToggle = props => {
  // here you have to use toggle, not value
  const { toggle, path, toggleSwitchHandler } = props;

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

export default OwnToggle;

And also you had to pass object instead of obj in App.js.

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

There should be a modification in your toggleSwitchHandler:

const toggleSwitchHandler = (path, e) => {
    const tempObject = { ...object };
    set(tempObject, path, !get(object, path)); // get from lodash
    setObject({ ...object, ...tempObject });
};
Related