简体   繁体   中英

why my state basket stay empty when i try to push data inside ? [REACT JS]

i can't figure why my state doesn't get set.

I need to add product in my kart, but the kart stay empty or i don't know,

i have a product in my array on click, that's fine, but when i click on an other product, the new one take the place of the first one.

Does any one has an idea?

here's my code

const Card = ({ card }) => {
  const [basket, setBasket] = useState([]);

  useEffect(() => {
    // console.log('basket', basket);
  });

  const handleBasketClick = (card) => {
    const newBasket = [...basket];

    let exist = newBasket.find((item) => {
      return item.id === card.id;
    });
    if (exist === undefined) {
      newBasket.push(card);
      card.quantity = 1;
      // console.log('push in cart', newBasket);
    } else {
      card.quantity++;
      // console.log('add quantity', newBasket);
    }
    setBasket(newBasket);
    // console.log('newBasket', newBasket);
  };

  return (
    <li>
      <h1>{card.name}</h1>
      <img
        src={card.imageUrl || card.images.small}
        alt={`${card.name} `}
      />
      <div
        onClick={() => handleBasketClick(card)}
      >
        Add to basket
      </div>
    </li>
  );
};

export default PokeCard;

I think you need to change your handler logic to this. I also suggest that you move this function to the parent component, as the parent component should own the state.

const handleBasketClick = (card) => {
    const newBasket = [...basket];

    const exist = newBasket.find((item) => item.id === card.id);
    const targetIndex = newBasket.findIndex((item) => item.id === card.id);

    let updatedBasket;

    if (exist === undefined) {
         card.quantity = 1;
         updatedBasket = [...newBasket, card];
    } else {
         card.quantity++;
         newBasket[targetIndex] = card;
         updatedBasket = newBasket;
    }

    setBasket(updatedBasket);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM