I wanted to filter through my array of objects. Could someone explain me why the first example does not work? When i type into an input it just deletes my objects. However the 2nd example works fine. What is the best way of doing a filtering?
1st example (not working):
const [data, setData] = useState(JSON.parse(localStorage.getItem("notes") ?? "[]"));
const [inputValue, setInputValue] = useState("");
const handleNoteListFilter = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
const filteredNotes = data.filter((val) =>
val.text.toLowerCase().includes(inputValue)
);
setData(filteredNotes);
};
return (
<>
<input onChange={(e) => handleNoteListFilter(e)} value={inputValue}/>
{data.map((note) => (
<Note
key={note.id}
note={note}
onExpandCheck={setIsExpandedCheck}
onNoteDelete={handleNoteDelete}
onNoteSave={handleNoteSave}
/>
))}
</>
)
2nd example(working):
const [data, setData] = useState(JSON.parse(localStorage.getItem("notes") ?? "[]"));
const [inputValue, setInputValue] = useState("");
return (
<>
<input onChange={(e) => setInputValue(e.target.value)} value={inputValue}/>
{data
.filter((val) => val.text.toLowerCase().includes(inputValue))
.map((note) => (
<Note
key={note.id}
note={note}
onExpandCheck={setIsExpandedCheck}
onNoteDelete={handleNoteDelete}
onNoteSave={handleNoteSave}
/>
))}
</>
)
datawith a filtered set of objects with every input change in the first one, and display those remaining objects. In the second you're not setting state - just filtering the objects (which returns a new array), and then mapping over that array. The state is still intact.