1- import { useState } from "react" ;
1+ import { useState , useMemo } from "react" ;
22import { SnippetType } from "../types" ;
33import { useAppContext } from "../contexts/AppContext" ;
44import { useSnippets } from "../hooks/useSnippets" ;
55
66import SnippetModal from "./SnippetModal" ;
7- import { LeftAngleArrowIcon } from "./Icons" ;
87
9- const SnippetList = ( ) => {
8+ const SnippetList = ( { query } : { query ?: string | null } ) => {
109 const { language, snippet, setSnippet } = useAppContext ( ) ;
11- const { fetchedSnippets } = useSnippets ( ) ;
10+ const { fetchedSnippets, loading } = useSnippets ( ) ;
1211 const [ isModalOpen , setIsModalOpen ] = useState ( false ) ;
1312
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 ( ) )
1917 ) ;
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 > ;
2023
2124 const handleOpenModal = ( activeSnippet : SnippetType ) => {
2225 setIsModalOpen ( true ) ;
@@ -31,7 +34,7 @@ const SnippetList = () => {
3134 return (
3235 < >
3336 < ul role = "list" className = "snippets" >
34- { fetchedSnippets . map ( ( snippet , idx ) => (
37+ { filteredSnippets . map ( ( snippet , idx ) => (
3538 < li key = { idx } >
3639 < button
3740 className = "snippet | flow"
@@ -41,8 +44,10 @@ const SnippetList = () => {
4144 < div className = "snippet__preview" >
4245 < img src = { language . icon } alt = { language . lang } />
4346 </ div >
44-
4547 < h3 className = "snippet__title" > { snippet . title } </ h3 >
48+ { query && (
49+ < p className = "snippet__description" > { snippet . description } </ p >
50+ ) }
4651 </ button >
4752 </ li >
4853 ) ) }
0 commit comments