vendredi 11 décembre 2020

Adding or removing from an array based on if it includes event

I am trying to have a single button that will add the value to the array, or if the value already exists in the array to remove that value.
The array is called toppings

const ToppingPlusMinus = (e) => {
  if (toppings.includes(e.target.value, 1)) {
    removeTopping(e)
  }
  else {
    changeToppings(e);
  }
}

The two functions

const removeTopping = (e) => {
  toppings.splice(e.target.value)
}

const changeToppings = (e) => {
    setToppings([...toppings, e.target.value]);
  };

The buttons are toppings on a pizza, and they are in this format

<button
            type="button"
            value="Sausage, "
            className="button btn first"
            onClick={(event) => {
              ToppingPlusMinus(event);
            }}
          >
            Sausage
          </button>

This works fine for adding the value to the array, however on removal there are unexpected outcomes.

  1. the item only is removed after the user double clicks the button
  2. the removal also removes the topping before it in the array.
  3. the button does not stay in its active state while the item is in the array (I haven't attempted this, but if anyone know how to do it I'd be appreciative)


I have set up a codesandbox with my code here I appreciate your help.

Aucun commentaire:

Enregistrer un commentaire