MCPcopy Create free account
hub / github.com/code100x/cms / SearchBar

Function SearchBar

src/components/search/SearchBar.tsx:25–221  ·  view source on GitHub ↗
({ onCardClick, isMobile = false }: SearchBarProps)

Source from the content-addressed store, hash-verified

23}
24
25export function SearchBar({ onCardClick, isMobile = false }: SearchBarProps) {
26 const [state, setState] = useState({
27 open: false,
28 searchTerm: '',
29 commandSearchTerm: '',
30 searchedVideos: null as TSearchedVideos[] | null,
31 isInputFocused: false,
32 loading: false,
33 selectedIndex: -1,
34 });
35
36 const debouncedSearchTerm = useDebounce(state.searchTerm, 300);
37 const debouncedCommandSearchTerm = useDebounce(state.commandSearchTerm, 300);
38
39 const ref = useRef<HTMLDivElement>(null);
40 const router = useRouter();
41
42 useClickOutside(ref, () => {
43 setState((prev) => ({ ...prev, isInputFocused: false }));
44 });
45
46 const fetchData = useCallback(async (term: string) => {
47 setState((prev) => ({ ...prev, loading: true }));
48
49 try {
50 const response = await fetch(`/api/search?q=${encodeURIComponent(term)}`);
51 if (!response.ok) {
52 throw new Error('Network response was not ok');
53 }
54 const data = await response.json();
55 setState((prev) => ({ ...prev, searchedVideos: data, loading: false }));
56 } catch (err) {
57 toast.error('Something went wrong while searching for videos');
58 setState((prev) => ({
59 ...prev,
60 commandSearchTerm: '',
61 searchTerm: '',
62 searchedVideos: null,
63 loading: false,
64 }));
65 }
66 }, []);
67
68 useEffect(() => {
69 if (debouncedSearchTerm.trim().length > 2) {
70 fetchData(debouncedSearchTerm);
71 } else {
72 setState((prev) => ({ ...prev, searchedVideos: null }));
73 }
74 }, [debouncedSearchTerm, fetchData]);
75
76 useEffect(() => {
77 if (debouncedCommandSearchTerm.trim().length > 2) {
78 fetchData(debouncedCommandSearchTerm);
79 } else {
80 setState((prev) => ({ ...prev, searchedVideos: null }));
81 }
82 }, [debouncedCommandSearchTerm, fetchData]);

Callers

nothing calls this directly

Calls 2

useDebounceFunction · 0.90
useClickOutsideFunction · 0.85

Tested by

no test coverage detected