Abdullah Mujahid
Abdullah Mujahid

Reputation: 917

State isn't getting update correctly React

I have been working on a React Project and I am facing an issue that when I click on Add to Cart and select either the checkbox it will ignore the 1st click of the checkbox when I uncheck the check box and then again I click on it then it will add the value into the cart. I am unable to figure it out why I am getting this error.

class Something extends Component {
  constructor(props) {
    super(props);

    let defaultOptionValues = {};
    this.props.product.options.forEach((selector) => {
      defaultOptionValues[selector.name] = selector.values[0].value;
    });
    this.state = { selectedOptions: defaultOptionValues };

    this.handleOptionChange = this.handleOptionChange.bind(this);
    this.handleQuantityChange = this.handleQuantityChange.bind(this);
  }
  handleOptionChange(event) {
    const target = event.target;
    let selectedOptions = this.state.selectedOptions;
    selectedOptions[target.name] = target.value;
    const selectedVariant = this.props.client.product.helpers.variantForOptions(
      this.props.product,
      selectedOptions
    );

    this.setState({
      selectedVariant: selectedVariant,
      selectedVariantImage: selectedVariant.attrs.image,
    });
  }


  handleQuantityChange(event) {
    this.setState({
      selectedVariantQuantity: event.target.value,
    });
  }

  render() {
    const { title, images, options } = this.props.product;
    let variantImage =
      this.state.selectedVariantImage || this.props.product.images[0];
    let variant = this.state.selectedVariant || this.props.product.variants[0];
    let variantQuantity = this.state.selectedVariantQuantity || 1;
    let SelectedTwoAccessoriesQuantity = 0;
    let SelectedFourAccessoriesQuantity = 0;
    let discountedPrice = variant.price * 0.8;
    let roundedPrice = discountedPrice.toFixed(2);
    const addToCartButton = (
      <button
        className="body-text"
        onClick={() => {
          this.props.addVariantToCart(variant.id, variantQuantity) &&
            this.props.addVariantToCart(
              this.props.accessories.variants[0].id,
              SelectedTwoAccessoriesQuantity + SelectedFourAccessoriesQuantity
            );
        }}
      >
        Add To Cart
      </button>
    );
    // QUANTITY FIELD
    const quantityField = (
      <label>
        <input
          className="body-text"
          min="1"
          type="number"
          defaultValue={variantQuantity}
          onChange={this.handleQuantityChange}
        ></input>
      </label>
    );
    
    function onChange(e) {
      console.log(`checked = ${e.target.checked}`);
    }

    <Checkbox onChange={onChange}>Checkbox</Checkbox>;
    return (
      <>
        <Container className="mattress-container" fluid={true}>
                    <span className="discountP">10% off</span>
                     <p className="mattress-size">Size</p>
                    {variantSelectors}
                    <div>
                      <Row className=" accessories-stlye">
                        <span>Accessories</span>{" "}
                      </Row>

                      <Row className="Checkbox-1">
                        <Col md="10">
                          <Checkbox
                            onChange={(e) => {
                              const isChecked = e.target.checked;
                              isChecked && (SelectedTwoAccessoriesQuantity = 2);
                              !isChecked &&
                                (SelectedTwoAccessoriesQuantity = 0);
                            }}
                            style={{ marginLeft: "-17px" }}
                          />{" "}
                          <span>x2</span>{" "}
                        </Col>
                        <Col md="2">
                          <span>
                            ${this.props.accessories.variants[0].price * 2}
                          </span>
                         
                        </Col>
                      </Row>

                      <Row className="Checkbox-1">
                        <Col md="10">
                          <Checkbox
                            onChange={(e) => {
                              const isChecked = e.target.checked;
                              
                              isChecked &&
                                (SelectedFourAccessoriesQuantity = 4);
                              !isChecked &&
                                (SelectedFourAccessoriesQuantity = 0);

                                console.log(SelectedFourAccessoriesQuantity)
                            }}
                            style={{ marginLeft: "-17px" }}
                          />{" "}
                          <span>x4 </span>
                        </Col>
                       
                        <Col md="2">
                          <span>
                            {console.log(this.props.accessories.variants[0].price * 4)}
                            ${this.props.accessories.variants[0].price * 4}
                          </span>
                        </Col>
                      </Row>

I have tried to remove all the irrelevant code to make it easier to be understood. For example, if I click on x4 it should add 4 times and the mattress should also be added once. But what it is doing is skipping pillows and adding only the mattress. When I uncheck and again click on the check box then it adds the value to the cart.

Upvotes: 2

Views: 82

Answers (3)

Seyed Kazem Mousavi
Seyed Kazem Mousavi

Reputation: 457

this.setState({
      selectedVariant: selectedVariant,
      selectedVariantImage: selectedVariant.attrs.image,
    });

You should define the parameters =>selectedVariant,selectedVariantImage

this.state = { selectedOptions: defaultOptionValues,
selectedVariant:'',
selectedVariantImage:''
 };

and define each state you want to use

Upvotes: 0

Seyed Kazem Mousavi
Seyed Kazem Mousavi

Reputation: 457

you can use arrow function and you can don't use bind

const handleOptionChange = (event) => {
    const target = event.target;
    let selectedOptions = this.state.selectedOptions;
    selectedOptions[target.name] = target.value;
    const selectedVariant = this.props.client.product.helpers.variantForOptions(
      this.props.product,
      selectedOptions
    );

    this.setState({
      selectedVariant: selectedVariant,
      selectedVariantImage: selectedVariant.attrs.image,
    });
  }

Upvotes: 0

Aiman_Irfan
Aiman_Irfan

Reputation: 375

Try to bind the onChange function because I see that your onChange function is not bind.

Upvotes: 1

Related Questions