Skip to content

How to add all filtered elements in an state varaible

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.

const searchUsers = () => {
    items.filter((item) => {
      if (searchTerm === null) {
        setItems([...items]);
        return item;
      } else if (item.title.toLowerCase().includes(searchTerm)) {
        setItems([item]);
      }
    });
  };

Answer

You can try useMemo hook for this. You dont even need to update the state for filtered results.

const searchResults = useMemo(() => {
  if (!searchTerm) {
    return items;
  }

  return items?.filter((item) =>
    item?.toLowerCase()?.includes(searchTerm?.toLowerCase().trim())
  );
}, [items, searchTerm]);

You can directly use the searchResults while rendering your table.