Home > Software design >  React.js, Array.filter not filtering out items that doesn't meet the condition
React.js, Array.filter not filtering out items that doesn't meet the condition

Time:01-03

I'm working on a shopping cart in React, and to be able to delete single items, I want to compare the id of the item with the id of all the items in the array, so that if the id are the same, I can filter out that item from the array. However the filter method doesn't seem to work. Am I missing something?

Function:

const deleteItem = () => {
    cartArray.map((e) => {
      console.log("I'm working");
      if (e.id != id) {
        setCartArray(cartArray.filter((e) => e.id !== id));
      }
    });
  };

Component where function is called:

const CartProduct = ({
  cartArray,
  setCartArray,
  imgUrl,
  nameUrl,
  priceUrl,
  id,
}) => {
  const shortenProductName = (name) => {
    if (name.length > 40) return name.slice(0, 40)   "...";
    else return name;
  };

  const deleteItem = () => {
    cartArray.map((e) => {
      console.log("I'm working");
      if (e.id != id) {
        setCartArray(cartArray.filter((e) => e.id !== id));
      }
    });
  };
  

  return (
    <div className="cart-product">
      <p></p>
      <img src={imgUrl} alt="product image" />
      <div className="name-price-container">
        <p>{shortenProductName(nameUrl)}</p>
        {/* <p>{nameUrl.slice(0, )   "..."}</p> */}
        <h4>€ {priceUrl}</h4>
      </div>
      <DeleteIcon onClick={deleteItem} />
    </div>
  );
};

Thank you!

CodePudding user response:

You should probably remove the whole .map part. Also, pass the id into the function.

const deleteItem = id => {
   setCartArray(cartArray.filter(e => e.id !== id));
};

CodePudding user response:

The filter() method creates a new array with all elements that pass the test implemented so you can just filter the cartArray with the filter function solely.

const deleteItem = () => {
   setCartArray(cartArray.filter(e => e.id !== id));
};

CodePudding user response:

You dont need the map and I would probably simplify the whole thing. Here a working example: https://codesandbox.io/s/wizardly-wilson-fxwje?file=/src/App.js

import React from "react";

export default function App() {
  const [cartArray, setCartArray] = React.useState([
    { id: 1, title: "first" },
    { id: 2, title: "second" },
    { id: 3, title: "third" }
  ]);

  const deleteItem = (e) => {
    setCartArray(
      cartArray.filter(
        (cartItem) => parseInt(e.target.value, 10) !== cartItem.id
      )
    );
  };

  return (
    <div className="App">
      <div>
        {cartArray.map((item) => {
          return (
            <button onClick={deleteItem} value={item.id}>
              {item.title}
            </button>
          );
        })}
      </div>
    </div>
  );
}
  • Related