How to add only 1 time the same item in the cart ? (Javascript)

Asked

Viewed 34 times

-1

How would you add only 1 time the same item in the cart?

import React, { Component } from "react";
import * as S from './styles'

//Components
import ImgCar from '../src/components/imgs/car.svg';

class Car extends Component {

  state = {
    carAdd: [],
    car: [
      {
        id: 0,
        name: "Jetta",
        assembler: "Volkswagen",
        price: 144000,
        type: "Sedan",
        btnDisabled: false
      },
      {
        id: 1,
        name: "Polo",
        assembler: "Volkswagen",
        price: 70000,
        type: "Hatch",
        btnDisabled: false
      },
      {
        id: 2,
        name: "T-Cross",
        assembler: "Volkswagen",
        price: 123000,
        type: "SUV",
        btnDisabled: false
      }
     
    ]
  }

  funcBtnAdd = (event) => {
    const check = this.state.car.filter(item => item.id == event.id);
    event.btnDisabled = true;
    console.log(check)
    this.setState({
      carAdd: this.state.carAdd.concat(check)
    })
  }

1 answer

-2

If checking is the car to be added, would do the following:

  funcBtnAdd = (event) => {
    const check = this.state.car.filter(item => item.id == event.id);
    event.btnDisabled = true;

    const isCarAlreadyAdded = this.carAdd.some(car => car.id === check.id);
    
    if (!isCarAlreadyAdded) {
      this.setState(prevState => ({
        carAdd: [...prevState, check]
      }))
    }
  }

Explanation: The function some returns true if the condition passed is true. Then, it checks whether in the array of cars already added (carAdd) there is already the new car to be inserted. If yes, the value of the isCarAlreadyAdded variable will be true, and the state will not be updated.

  • Thank you very much, I understood the logic. I will test here and I already pass if you gave bug or if ta ok. thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.