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

230
Views
React - filter deletes all items instead of one

I fail to understand why .filter deletes all items instead of one even though the key should be unique. Why? I think it should filter out the id that is in the function, but it keeps deleting everything, because of the .map, right?

const App = () => {
  const [state, setState] = useState("")
  const [list, updateList] = useState([])

  const addItem = () => {
    list.push(state)
    setState('')
    updateList(list)
  }

  const removeItem = (id) => {
    updateList(list.filter((item) => item.id !== id));
  
  }

  return (
    <div>
        <input placeholder='type...' value={state} onChange={(e) => setState(e.target.value)}></input>
        <button onClick={addItem}>Submit</button>
      {list.map((item) => (
        <>
            <div key={item.id}>{item}</div>
            <button onClick={() => removeItem(item.id)}>delete</button>
            </>
        )
      )}
    </div>
  )
}

export default App
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You dont have item.id actually, you just have item which is a string. You add items to that array from the text box, so you only have Array of strings

What you should do is remove by item not item.id

your code should be something like that remoteItem function :

const removeItem = (selectedItem) => {
updateList(list.filter((item) => item !== selectedItem));

};

Then in your list.map

{list.map((item) => (
        <>
          <div key={item}>{item}</div>
          <button onClick={() => removeItem(item)}>delete</button>
        </>
      ))}
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!