1
1
import type { Product } from '@/env'
2
+
3
+ import { useState } from 'react'
4
+
2
5
import { useStoreProducts } from '@/stores/storeProducts'
3
6
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
+
4
17
export const SearchProducts = ( ) => {
5
18
const { cacheProducts, setSearchProducts } = useStoreProducts ( )
19
+ const [ searchTerm , setSearchTerm ] = useState ( '' )
6
20
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
9
26
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
+ }
11
37
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
+ } )
21
47
22
48
setSearchProducts ( products2 )
49
+ } , 300 )
50
+
51
+ const handleChange = ( e : React . ChangeEvent < HTMLInputElement > ) => {
52
+ const value = e . target . value
53
+ setSearchTerm ( value )
54
+ handleSearch ( value )
23
55
}
24
56
25
57
return (
@@ -28,7 +60,8 @@ export const SearchProducts = () => {
28
60
type = "text"
29
61
className = "bg-transparent w-full h-full p-2"
30
62
placeholder = "Buscar productos"
31
- onChange = { searchProducts }
63
+ value = { searchTerm }
64
+ onChange = { handleChange }
32
65
/>
33
66
34
67
< svg
0 commit comments