Reputation: 86
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}
/>
))}
</>
)
Upvotes: 0
Views: 34
Reputation: 370779
In the first approach, every time you change the state of the data
, you're filtering out elements from the array. If you filter out an element during one render, it will never appear again in the lifetime of the component. When creating the new state, you need to filter not the current displayed array (which probably has values missing), but the original array from storage.
Also keep in mind that state setters are asynchronous, so
setInputValue(e.target.value);
won't change inputValue
until the next render.
const originalData = useMemo(() => JSON.parse(localStorage.getItem("notes") ?? "[]"), []);
const [data, setData] = useState(originalData);
const [inputValue, setInputValue] = useState("");
const handleNoteListFilter = (e: React.ChangeEvent<HTMLInputElement>) => {
const newInputValue = e.target.value;
setInputValue(newInputValue);
const filteredNotes = originalData.filter((val) =>
val.text.toLowerCase().includes(newInputValue)
);
setData(filteredNotes);
};
Upvotes: 2