1
- import { useState } from "react" ;
1
+ import { useState , useMemo } from "react" ;
2
2
import { SnippetType } from "../types" ;
3
3
import { useAppContext } from "../contexts/AppContext" ;
4
4
import { useSnippets } from "../hooks/useSnippets" ;
5
5
6
6
import SnippetModal from "./SnippetModal" ;
7
- import { LeftAngleArrowIcon } from "./Icons" ;
8
7
9
- const SnippetList = ( ) => {
8
+ const SnippetList = ( { query } : { query ?: string | null } ) => {
10
9
const { language, snippet, setSnippet } = useAppContext ( ) ;
11
- const { fetchedSnippets } = useSnippets ( ) ;
10
+ const { fetchedSnippets, loading } = useSnippets ( ) ;
12
11
const [ isModalOpen , setIsModalOpen ] = useState ( false ) ;
13
12
14
- if ( ! fetchedSnippets )
15
- return (
16
- < div >
17
- < LeftAngleArrowIcon />
18
- </ div >
13
+ const filteredSnippets = useMemo ( ( ) => {
14
+ if ( ! query ) return fetchedSnippets ;
15
+ return fetchedSnippets . filter ( ( snippet ) =>
16
+ snippet . title . toLowerCase ( ) . includes ( query . toLowerCase ( ) )
19
17
) ;
18
+ } , [ fetchedSnippets , query ] ) ;
19
+
20
+ if ( loading ) return < div > Loading...</ div > ;
21
+ if ( ! filteredSnippets || filteredSnippets . length === 0 )
22
+ return < div > No results found for "{ query } "</ div > ;
20
23
21
24
const handleOpenModal = ( activeSnippet : SnippetType ) => {
22
25
setIsModalOpen ( true ) ;
@@ -31,7 +34,7 @@ const SnippetList = () => {
31
34
return (
32
35
< >
33
36
< ul role = "list" className = "snippets" >
34
- { fetchedSnippets . map ( ( snippet , idx ) => (
37
+ { filteredSnippets . map ( ( snippet , idx ) => (
35
38
< li key = { idx } >
36
39
< button
37
40
className = "snippet | flow"
@@ -41,8 +44,10 @@ const SnippetList = () => {
41
44
< div className = "snippet__preview" >
42
45
< img src = { language . icon } alt = { language . lang } />
43
46
</ div >
44
-
45
47
< h3 className = "snippet__title" > { snippet . title } </ h3 >
48
+ { query && (
49
+ < p className = "snippet__description" > { snippet . description } </ p >
50
+ ) }
46
51
</ button >
47
52
</ li >
48
53
) ) }
0 commit comments