jan.kowalski
jan.kowalski

Reputation: 105

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

Upvotes: 3

Views: 69

Answers (3)

andsilver
andsilver

Reputation: 5972

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 });
};

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53874

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

Upvotes: 2

Rostyslav
Rostyslav

Reputation: 2856

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} />

Upvotes: 1

Related Questions