Skip to content

Commit

Permalink
chore: removed unused code and moved search filter to custom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
nomadbitcoin committed Sep 26, 2024
1 parent c04c9ea commit e5883e0
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 244 deletions.
240 changes: 0 additions & 240 deletions components/Filter/utils.js

This file was deleted.

17 changes: 17 additions & 0 deletions hooks/useFilterState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useState, useEffect } from 'react'
import { filterItems } from '../utils/filterItems'

// Custom hook to manage filter state
export const useFilterState = (data, searchQuery) => {
const [filteredData, setFilteredData] = useState([])

useEffect(() => {
const searchFields = ['title', 'description'] // Fields to search for courses
const filtered = filterItems(data, searchQuery, searchFields)
setFilteredData(filtered)
}, [data, searchQuery])

return {
filteredData,
}
}
7 changes: 3 additions & 4 deletions pages/courses/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ import { Container } from '@nextui-org/react'
import { CourseCard } from '../../components/Card/Course'
import { useTranslation } from 'react-i18next'
import SearchBar from '../../components/SearchBar'
import { useFilterState } from '../../components/Filter/utils'
import { useFilterState } from '../../hooks/useFilterState'

function Courses({ allCourses }) {
const { t } = useTranslation()
const [showMore, setShowMore] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
const { filteredCourses } = useFilterState(allCourses, searchQuery, 'course')
const { filteredData } = useFilterState(allCourses, searchQuery)

return (
<>
Expand Down Expand Up @@ -39,7 +38,7 @@ function Courses({ allCourses }) {
setSearchQuery={setSearchQuery}
placeholder={t('searchBuild')}
/>
{filteredCourses.map((c) => {
{filteredData.map((c) => {
return (
<>
<CourseCard course={c} />
Expand Down
20 changes: 20 additions & 0 deletions utils/filterItems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Utility function to filter items based on search query
export const filterItems = (items, searchQuery, searchFields = []) => {
return items.filter((item) => {
return searchFields.some((field) => {
let content = ''
if (field === 'title' && item.metadata) {
// Get all titles from the metadata
const titles = Object.values(item.metadata)
.filter((meta) => meta?.title)
.map((titleObj) => titleObj.title)
// Check if any of the titles includes the search query
return titles.some((title) => title.toLowerCase().includes(searchQuery.toLowerCase()))
} else {
content = item[field]
}

return content && content.toLowerCase().includes(searchQuery.toLowerCase())
})
})
}

0 comments on commit e5883e0

Please sign in to comment.