dimanche 22 décembre 2019

Updating array in react state, using concat

I have a component of checkbox, basically what im trying to do is to make array of the checked ones and send the information to an api. but im having trouble updating the state array without deleteing the last object inserted. im using concat and still same result. here is the code for the whole component:

import React, { Fragment, Component } from 'react';
import { Inputt, Checkbox } from './style';

interface Istate {
  checked: boolean;
  products?: any[];
}
interface Iprops {
  id: any;
  value: any;
  changeValue?: (checkBoxId: string, value: any) => void;
}
class CheckBoxComp extends Component<Iprops, Istate> {
  state = {
    checked: true,
    products: [] as any,
  };

  addOne = (id: any, checked: any) => {
    let { products } = this.state;
    const newObj = { id, checked };
    products = products.concat(newObj);
    this.setState({ products }, () => {
      console.log(products);
    });
  };

  isChecked = (id: any) => {
    const { checked, products } = this.state;
    const { changeValue } = this.props;
    this.setState({
      checked: !checked,
    });
    if (changeValue) {
      changeValue(id, checked);
    }
    this.addOne(id, checked);
  };

  render() {
    const { id, value } = this.props;
    const { checked, products } = this.state;
    return (
      <Fragment>
        <Checkbox>
          <span />{' '}
          <label className="checkbox-wrapper">
            <span className="display" />
            <Inputt
              type="checkbox"
              value={checked}
              onChange={() => {
                this.isChecked(id);
              }}
            />
            <span className="checkmark" />
          </label>
        </Checkbox>
      </Fragment>
    );
  }
}

export default CheckBoxComp;



Aucun commentaire:

Enregistrer un commentaire