0

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;

1 Answer 1

1

You can try this approach which utilizes the spread operator to make an array copy:

addOne = (id: any, checked: any) => {
    this.setState((state: Istate): Partial<Istate> => ({
        products: [
            ...state.products,
            { id, checked },
        ],
    }), () => console.log(this.state.products));
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.