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
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>
</>
))}