Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: useSidebarSearch.ts to ⚒️✨ #1454

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 26 additions & 20 deletions hooks/useSidebarSearch.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,58 @@
import useSearch from './useSearch'
import { sidebarData } from '../database/data'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import useSearch from './useSearch';
import { sidebarData } from '../database/data';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';

interface SidebarItem {
name: string;
url?: string;
resources: { name: string }[];
subcategory: { name: string; resources: { name: string }[] }[];
}

function useSidebarSearch() {
const { setSearch, debouncedSearch } = useSearch()
const [searchResults, setSearchResults] = useState(sidebarData)
const router = useRouter()
const { setSearch, debouncedSearch } = useSearch();
const [searchResults, setSearchResults] = useState<SidebarItem[]>(sidebarData);
const router = useRouter();

useEffect(() => {
const filteredResults = sidebarData.filter((sidebarItem) =>
sidebarItem.subcategory.some((subcategory) => matchSearch(subcategory))
)
);

const mappedResults = filteredResults.map((sidebarItem) => ({
...sidebarItem,
subcategory: sidebarItem.subcategory.filter((subcategory) =>
matchSearch(subcategory)
),
}))
}));

setSearchResults(mappedResults)
setSearchResults(mappedResults);

if (debouncedSearch.length > 0) {
router.push({
pathname: '/search',
query: {
query: debouncedSearch,
},
})
});
}
}, [debouncedSearch])
}, [debouncedSearch]);

function matchSearch(item: { name: any; url?: string; resources: any }) {
const itemName = item.name.toLowerCase()
function matchSearch(item: { name: string; resources: { name: string }[] }) {
const itemName = item.name.toLowerCase();
const matchingResources = item.resources.filter(
(resource: { name: string }) =>
resource.name.toLowerCase().includes(debouncedSearch.toLowerCase())
)
(resource) => resource.name.toLowerCase().includes(debouncedSearch.toLowerCase())
);

return (
debouncedSearch.length < 1 ||
itemName.includes(debouncedSearch.toLowerCase()) ||
matchingResources.length > 0
)
);
}

return { setSearch, searchResults, debouncedSearch }
return { setSearch, searchResults, debouncedSearch };
}

export default useSidebarSearch
export default useSidebarSearch;