i have an array of objects containing users data stored in a state varaible
and a table where I am displaying these users. I have a search field where a user can type name and search. Now my question is when a user types i want to search from these names and update the state variable and when user clears the input ,that time i want to show all users.in simple terms a search functionality.
JavaScript
x
11
11
1
const searchUsers = () => {
2
items.filter((item) => {
3
if (searchTerm === null) {
4
setItems([items]);
5
return item;
6
} else if (item.title.toLowerCase().includes(searchTerm)) {
7
setItems([item]);
8
}
9
});
10
};
11
Advertisement
Answer
You can try useMemo hook for this. You dont even need to update the state for filtered results.
JavaScript
1
11
11
1
const searchResults = useMemo(() => {
2
if (!searchTerm) {
3
return items;
4
}
5
6
return items?.filter((item) =>
7
item?.toLowerCase()?.includes(searchTerm?.toLowerCase().trim())
8
);
9
}, [items, searchTerm]);
10
11
You can directly use the searchResults
while rendering your table.