Home > Net >  state is not giving exact data on a button click
state is not giving exact data on a button click

Time:10-16

so, Here i have 3 products each has it's add to cart button and it's category like color, size, and quantity. im getting proper console when i select one product category and press add to cart button. the problem happens when user select 1st product category and without pressing add to cart button, user goes and select 3rd product category then user comes back and press 1st product's add to cart button it console the category's of 3rd product. any ideas to sort out this issue. check out the code below. Feel free to ask any questions.

 import "./Card.css";
import { useState } from "react";

function Card() {
  const [items, setItems] = useState({});

  const handleChageCategory = (key, event) => {
    setItems((oldState) => ({ ...oldState, [key]: event.target.value }));
  };

  const submitHandler = () => {
    console.log(items);
    setItems({});
  };

  return (
    <div className="main-container">
      <div className="container">
        <div className="image-container">
          <img
            src="https://images.pexels.com/photos/9558601/pexels-photo-9558601.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            alt=""
          />
        </div>
        <h2> T-Shirt </h2>
      </div>
      <div className="form-conatiner">
        <div className="selectors">
          <p>Solid Round Neck T-shirt</p>
          <select
            id="color"
            name="color"
            required
            onChange={(event) => handleChageCategory("color", event)}
          >
            <option>Color</option>
            <option value="black">Black</option>
            <option value="green">Green</option>
            <option value="orange">Orange</option>
          </select>

          <select
            name="quantity"
            required
            onChange={(event) => handleChageCategory("quantity", event)}
          >
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>

          <select
            name="size"
            required
            onChange={(event) => handleChageCategory("size", event)}
          >
            <option>Size</option>
            <option value="medium">Medium</option>
            <option value="large">Large</option>
            <option value="small">Small</option>
          </select>
          <div>
            <button onClick={submitHandler}>Add to Cart</button>
          </div>
        </div>
      </div>
      {/* second product */}

      <div className="container">
        <div className="image-container">
          <img
            src="https://images.pexels.com/photos/440320/pexels-photo-440320.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            alt=""
          />
        </div>
        <h2> i-Watch </h2>
      </div>
      <div className="form-conatiner">
        <div className="selectors">
          <p>Dizo watch with amlod </p>
          <select
            id="2"
            name="color"
            required
            onChange={(event) => handleChageCategory("brand", event)}
          >
            <option>Brand</option>
            <option value="Apple">Apple</option>
            <option value="Samsung">Samsung</option>
            <option value="Pixel">Pixel</option>
          </select>

          <select
            name="qantity"
            required
            onChange={(event) => handleChageCategory("qantity", event)}
          >
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>

          <select
            name="type"
            required
            onChange={(event) => handleChageCategory("type", event)}
          >
            <option>type</option>
            <option value="29mm">29mm</option>
            <option value="34mm">34mm</option>
            <option value="42mm">42mm</option>
          </select>
          <div>
            <button onClick={submitHandler}>Add to Cart</button>
          </div>
        </div>
      </div>
      {/* third product */}
      <div className="container">
        <div className="image-container">
          <img
            src="https://images.pexels.com/photos/1661471/pexels-photo-1661471.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            alt=""
          />
        </div>
        <h2> Hoodie </h2>
      </div>
      <div className="form-conatiner">
        <div className="selectors">
          <p>Adidas hoodie with zip </p>
          <select
            id="2"
            name="color"
            required
            onChange={(event) => handleChageCategory("color", event)}
          >
            <option>Color</option>
            <option value="Gray">gray</option>
            <option value="White">white</option>
            <option value="Cyan">cyan</option>
          </select>

          <select
            name="qantity"
            required
            onChange={(event) => handleChageCategory("qantity", event)}
          >
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>

          <select
            name="size"
            required
            onChange={(event) => handleChageCategory("size", event)}
          >
            <option>type</option>
            <option value="39(S)">39(S)</option>
            <option value="42(M)">42(M)</option>
            <option value="46(L)">46(L)</option>
          </select>
          <div>
            <button onClick={submitHandler}>Add to Cart</button>
          </div>
        </div>
      </div>
    </div>
  );
}
export default Card;

CodePudding user response:

I think what happens is that you only reset your state when the user adds to cart. So what happens is :

  • user selects category of the first item, so you store for example "color":"red"
  • then user selects the 3rd item color so you erase your previous "color" key in your store
  • user clicks add to card on product one so you actually add to cart the product one data but with any modified data coming from other clicks on other products that may have happened before the first clicks in the product one and the "add to cart" function call

what i meant is that you seem to save "[key]: event.target.value" but since many of your products add a "color" key when user selects from the list, it erases the previous one in your state

You should push a list of product objects in your store, with all their properties

CodePudding user response:

Try adding product as another key for handleChangeCategory, like:

const handleChangeCategory = (product, key, event) => {
  setItems({
    ...items,
    [product]: {
      ...items[product],
      [key]: event.target.value
    }
  });
};
...
onChange={(event) => handleChangeCategory('shirt', 'color', event)}

CodePudding user response:

You are using the same collection (items) for all the products, and whenever user changes properties of an item from any category, the state values change for that product. After that, it wouldn't matter which Add to Cart button you pressed.

I think what you need to do is separate the items you keep in the state for each product type.

Your current state object is like:

{
    color: "green",
    quantity: "3",
    size: "large"
}

You can change this to something like:

{
    product1: {
        color: "green",
        quantity: "3",
        size: "large"
    },
    product2: {
        brand: "Pixel"
        qantity: "1"
        type: "29mm"
    }
}

Update the changeHandler for accepting productType as input

const handleChageCategory = (productType, key, event) =>

And call submitHandler with the related productType:

const submitHandler = (productType) => {
    console.log(items[productType]);
    setItems({});
};

Hope this helps

  • Related