CCCC
CCCC

Reputation: 6471

React - checkbox not update when multiple unselect

When I click the + button to expand the group and click the checkbox of group 1, it executes as expected.

But the problem is,
If I click the checkbox of group 1 first and then expand the group by clicking + button,
It shows all user clicked which is correct, if I clicked the checkbox of group 1 again,
the checkbox of group 1 become unchecked, but the checkboxes of users do not get unchecked.

Reproduce step: refresh the page > Click group 1 checkbox > click + to expand > click group 1 checkbox again > then you'll see user checkbox do not become unselected

SandBox Link below:
https://codesandbox.io/s/dazzling-antonelli-gl9rm

enter image description here after Unselecting group 1, 2 checkboxes of users do not become unselected: enter image description here

Upvotes: 1

Views: 265

Answers (2)

bertdida
bertdida

Reputation: 5298

Your isExist method returns undefined instead of false, fix it to return always either true/false.

isExist = (id, group) => {
    if (!this.props.selected) {
      console.log("selected = null");
      return false;
    }

    return (
      this.props.selected.find((ele) => ele.id === group + id) !== undefined
    );
  };

This way you don't have to manually convert its return value to boolean using !!.

I suggest to also refactor your handleSelected method to

handleSelected = async (e) => {
  const { selected } = this.state;

  if (e.target.checked) {
    let temp = { id: e.target.id, name: e.target.name };
    return this.setState({ selected: [...selected, temp] });
  }

  this.setState({
    selected: selected.filter(({ id }) => id !== e.target.id)
  });
};

Edit distracted-hoover-ts7nr

Upvotes: 1

nir shabi
nir shabi

Reputation: 367

The issue you are experiencing is a result of a problem in the first render - as you can see - you have "undefined Contact". You need to solve this issue, and then the grouping will work as you desire.

Upvotes: 0

Related Questions