Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
Using .filter() for React's useState setter within a .forEach() loop

I need to remove objects from an array stored within cart's state.

This should be done by iterating through the strings stored within selectedCart's array. For each string for selectedCart that matches cart's string (within an object/key), it should remove that entire object.

The code below seems to only remove the object that matches selectedCart's string in last index ONLY.

So if it's

const [selectedCart, setSelectedCart] = ['test', 'this', 'data']
const [cart, setCart] = [{name: "this"}, {name: "data"}, {name: "test"}]

And each object's key (name) has the value of all these strings... only the string 'data' gets filtered. If I switch the first and last positions (so 'test' is last), only the string 'test' gets filtered.

const [cart, setCart] = useState([])
const [selectedCart, setSelectedCart] = []

selectedCart.forEach(selected => 
      setCart(cart.filter(entry => entry.name !== selected))
    )

Edit: For the recommendation on another question regarding .filter(), it seems to only be applicable outside of useState(). When I take a similar approach with vanilla javascript, it seems to work fine.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You have to be careful with setting the state multiple times at once. I think in this case you want to use a functional update like so

selectedCart.forEach(selected => 
      setCart(cart => cart.filter(entry => entry.name !== selected))
    )

Although speed-o-soundSonic's answer is probably ideal: setCart(cart.filter(entry => !selectedCart.includes(entry.name)))

about 4 years ago · Juan Pablo Isaza Report

0

here I am giving the full solution to your issue with UI. Please check it out.

let cartArr = [...cart];
const selectedCartArr = [...selectedCart];
selectedCartArr.forEach((selected) => {
  cartArr = cartArr.filter((el) => el.name !== selected);
});
setCart(cartArr);
setViewSelectedCart(selectedCartArr);

Kindly check my solution here:-https://codesandbox.io/s/react-filter-question1-y17dd?file=/src/App.js:851-961

    import "./styles.css";
    import { useEffect, useState } from "react";
    
    export default function App() {
      const dataArr = [
        { id: 1, name: "item a" },
        { id: 2, name: "item b" },
        { id: 3, name: "item c" },
        { id: 4, name: "item d" },
        { id: 5, name: "item e" }
      ];
      const [cart, setCart] = useState([]);
      const [selectedCart, setselectedCart] = useState([]);
      const [viewSelectedCart, setViewSelectedCart] = useState([]);
    
      useEffect(() => {
        const data = [...dataArr];
        setCart(data);
      }, []);
    
      const changeHandler = (event) => {
        const _thisName = event.target.dataset.name;
        const selectedCartArr = [...selectedCart];
        selectedCartArr.push(_thisName);
        setselectedCart(selectedCartArr);
      };
    
      const applyHandler = (event) => {
        let cartArr = [...cart];
        const selectedCartArr = [...selectedCart];
        selectedCartArr.forEach((selected) => {
          cartArr = cartArr.filter((el) => el.name !== selected);
        });
        setCart(cartArr);
        setViewSelectedCart(selectedCartArr);
      };
    
      return (
        <>
          <div className="wrapper">
            <div className="cart">
              <h3>Cart</h3>
    
              {cart.map((d) => {
                return (
                  <div key={d.id}>
                    <input
                      type="checkbox"
                      id={d.id}
                      onChange={changeHandler}
                      data-name={d.name}
                    />
                    <label htmlFor={d.id}>{d.name}</label>
                  </div>
                );
              })}
            </div>
            <div className="selectedCart">
              <h3>Selected Cart View</h3>
              <ol>
                {viewSelectedCart.map((el, i) => {
                  return <li key={i}>{el}</li>;
                })}
              </ol>
            </div>
          </div>
          <div className="button__wrapper">
            <button className="btn btn-apply" onClick={applyHandler}>
              Apply
            </button>
          </div>
        </>
      );
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!