Umbro
Umbro

Reputation: 2204

The value of the checkbox is added to the array but the checkbox is not checked

I have checked two checkboxes. I can unchecked them, but i can't again checked them. When unchecked checkboxes, the value is removed from the array peopleChecked, when them wants to mark the value is added to the array peopleChecked, but the checkboxes aren't checked

Code here:

class App extends Component {
  constructor() {
    super();
    this.state = {
      people: [
        {
          firstname: "Paul",
          userCompetences: [
            {
              asset: {
                id: "12345"
              }
            }
          ]
        },
        {
          firstname: "Victor",
          userCompetences: [
            {
              asset: {
                id: "5646535"
              }
            }
          ]
        },
        {
          firstname: "Martin",
          userCompetences: [
            {
              asset: {
                id: "097867575675"
              }
            }
          ]
        },
        {
          firstname: "Gregor",
          userCompetences: [
            {
              asset: {
                id: "67890"
              }
            }
          ]
        }
      ],
      peopleChecked: [
        {
          amount: 0, 
          asset: {
            id: "fgfgfgfg",
            name: 'Gregor'
          },
          asset_id: '67890'
        },
        {
          amount: 0,
          asset: {
            id: "dsdsdsd"
          },
          asset_id: '12345'
        },
      ],
      selectPeopleId: []
    }
  }

  handleSelect = (person) => {
    //Check if clicked checkbox is already selected
    var found = this.state.peopleChecked.find((element) => {
      return element.asset_id === person.userCompetences[0]['asset']['id'];
    });

    console.log(found);

    if(found){
      //If clicked checkbox already selected then remove that from peopleChecked array
      this.setState({
        peopleChecked: this.state.peopleChecked.filter(element => element.asset_id !== person.userCompetences[0]['asset']['id']),
        selectPeopleId: this.state.selectPeopleId.filter(element => element !== person.userCompetences[0]['asset']['id'])
      }, () => console.log(this.state.peopleChecked))
    }else{
      //If clicked checkbox is not already selected then add that in peopleChecked array
      this.setState({
        selectPeopleId: [...this.state.selectPeopleId,  person.userCompetences[0]['asset']['id']],
        peopleChecked: [...this.state.peopleChecked,  person]
      }, () => {console.log(this.state.selectPeopleId)})
    }
  }


  render() {
    return (
      <div>
        {this.state.people.map(person => (
          <div key={person.firstname} className="mb-1">
            <input
              type={'checkbox'}
              id={person.id}
              label={person.firstname}
              checked={
                this.state.peopleChecked.some(
                  ({ asset_id }) => asset_id === person.userCompetences[0]['asset']['id']
              )}
              onChange={() => this.handleSelect(person)}
            /> {person.firstname}
          </div>
        ))}
      </div>
    );
  }
}

Upvotes: 0

Views: 124

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15708

You can probably simplify your handleSelect logic a bit. Try breaking it down so you have an array of strings to work with. This is all you need just to toggle the checkboxes:

See sandbox with working code: https://stackblitz.com/edit/react-xsqhwt?file=index.js

  handleSelect = person => {
    const { peopleChecked } = this.state;
    let peopleCheckedClone = JSON.parse(JSON.stringify(peopleChecked));

    const personId = person.userCompetences[0].asset.id;

    const removeIndex = peopleChecked.findIndex(
      person => person.asset_id === personId
    );

    if (removeIndex >= 0) {
      peopleCheckedClone.splice(removeIndex, 1);
    } else {
      peopleCheckedClone = [...peopleCheckedClone, { asset_id: personId }];
    }

    this.setState({
      peopleChecked: peopleCheckedClone
    });
  };

Upvotes: 1

Related Questions