Skip to content

Commit ce241e0

Browse files
committed
mejora del buscador
1 parent 724367f commit ce241e0

File tree

2 files changed

+49
-13
lines changed

2 files changed

+49
-13
lines changed

.vscode/settings.json

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"CodeGPT.apiKey": "Ollama"
3+
}

src/allProducts/componentsIslands/SearchProducts.tsx

+46-13
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,57 @@
11
import type { Product } from '@/env'
2+
3+
import { useState } from 'react'
4+
25
import { useStoreProducts } from '@/stores/storeProducts'
36

7+
const debounce = (func: Function, delay: number) => {
8+
let timeoutId: ReturnType<typeof setTimeout> | undefined
9+
return (...args: any[]) => {
10+
if (timeoutId) clearTimeout(timeoutId)
11+
timeoutId = setTimeout(() => {
12+
func.apply(null, args)
13+
}, delay)
14+
}
15+
}
16+
417
export const SearchProducts = () => {
518
const { cacheProducts, setSearchProducts } = useStoreProducts()
19+
const [searchTerm, setSearchTerm] = useState('')
620

7-
const searchProducts = (e: any) => {
8-
const value = e.target.value
21+
const handleSearch = debounce((item: string) => {
22+
const value = item.toLowerCase().trim()
23+
const newValue = value.split(' ')
24+
25+
const filterLetters = newValue.length > 3
926

10-
const newValue = value.toLowerCase().trim().split(' ') as string[]
27+
const products2 = cacheProducts.filter((product: Product) => {
28+
if (filterLetters) {
29+
return (
30+
product?.title?.toLowerCase().includes(item) ||
31+
product?.category?.toLowerCase().includes(item) ||
32+
product?.brandProduct?.toLowerCase().includes(item) ||
33+
product?.collection?.toLowerCase().includes(item) ||
34+
product?.origin?.toLowerCase().includes(item)
35+
)
36+
}
1137

12-
const products2 = cacheProducts
13-
.map((product: Product) => {
14-
for (const word of newValue) {
15-
if (product?.title?.toLowerCase().includes(word)) {
16-
return product
17-
}
18-
}
19-
})
20-
.filter((product: Product) => product !== undefined)
38+
return newValue.some(
39+
(word) =>
40+
product?.title?.toLowerCase().includes(word) ||
41+
product?.category?.toLowerCase().includes(word) ||
42+
product?.brandProduct?.toLowerCase().includes(word) ||
43+
product?.collection?.toLowerCase().includes(word) ||
44+
product?.origin?.toLowerCase().includes(word)
45+
)
46+
})
2147

2248
setSearchProducts(products2)
49+
}, 300)
50+
51+
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
52+
const value = e.target.value
53+
setSearchTerm(value)
54+
handleSearch(value)
2355
}
2456

2557
return (
@@ -28,7 +60,8 @@ export const SearchProducts = () => {
2860
type="text"
2961
className="bg-transparent w-full h-full p-2"
3062
placeholder="Buscar productos"
31-
onChange={searchProducts}
63+
value={searchTerm}
64+
onChange={handleChange}
3265
/>
3366

3467
<svg

0 commit comments

Comments
 (0)