-
Notifications
You must be signed in to change notification settings - Fork 165
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor useSearch to be more generic
for reusability across pages
- Loading branch information
1 parent
63cf7e4
commit bd1e731
Showing
3 changed files
with
43 additions
and
41 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { useState } from "react"; | ||
|
||
export function useSearch<T = unknown[]>(items: T[], fieldNames: string[]) { | ||
const [filteredItems, setFilteredItems] = useState<T[]>(items); | ||
const handleSubmitKeywords = (keywords: string) => { | ||
const lowerKeywords = keywords.toLowerCase(); | ||
setFilteredItems( | ||
items.filter((item) => { | ||
const filterBy = (fieldName: keyof T) => { | ||
const selectedField = item[fieldName]; | ||
|
||
if (typeof selectedField === "string") { | ||
return selectedField.toLowerCase().includes(lowerKeywords); | ||
} else { | ||
return false; | ||
} | ||
}; | ||
|
||
const filterFunctions = fieldNames.map((fieldName) => | ||
filterBy(fieldName as keyof T) | ||
); | ||
return filterFunctions.reduce((acc, curr) => acc || curr, false); | ||
}) | ||
); | ||
}; | ||
return [filteredItems, handleSubmitKeywords] as const; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters