@@ -2,25 +2,27 @@ import Navbar from "./components/Navbar";
22import Stat from "./components/Stat" ;
33import StatsGenerator from "./components/StatsGenerator" ;
44import { useEffect , useState } from "react" ;
5- import { collection , getDocs } from "firebase/firestore" ;
5+ import { collection , getDocs , onSnapshot } from "firebase/firestore" ;
66import { firestore } from "./firebase" ;
77
88import "./App.css" ;
99
1010export default function App ( ) {
1111 const [ showStats , setShowStats ] = useState ( false ) ;
12-
1312 const [ data , setData ] = useState ( [ ] ) ;
13+ const [ filteredData , setFilteredData ] = useState ( [ ] ) ;
1414
1515 useEffect ( ( ) => {
1616 const getContacts = async ( ) => {
1717 try {
1818 const dataCollection = collection ( firestore , "users_stats" ) ;
19- const dataSnapshot = await getDocs ( dataCollection ) ;
20- const dataList = dataSnapshot . docs . map ( ( doc ) => {
21- return doc . data ( )
22- } )
23- setData ( dataList ) ;
19+ const unsubscribe = onSnapshot ( dataCollection , ( snapshot ) => {
20+ const dataList = snapshot . docs . map ( ( doc ) => doc . data ( ) ) ;
21+ setData ( dataList ) ;
22+ setFilteredData ( dataList ) ;
23+ } ) ;
24+ // Return a cleanup function to unsubscribe from the snapshot listener when the component unmounts
25+ return ( ) => unsubscribe ( ) ;
2426 } catch ( error ) {
2527 console . log ( error ) ;
2628 }
@@ -29,6 +31,13 @@ export default function App() {
2931 getContacts ( ) ;
3032 } , [ ] ) ;
3133
34+ const handleSearch = ( query ) => {
35+ const filtered = data . filter ( ( item ) =>
36+ item . username . toLowerCase ( ) . includes ( query . toLowerCase ( ) )
37+ ) ;
38+ setFilteredData ( filtered ) ;
39+ } ;
40+
3241 useEffect ( ( ) => {
3342 // Set an interval to toggle the animation class every 5 seconds
3443 const interval = setInterval ( ( ) => {
@@ -52,12 +61,12 @@ export default function App() {
5261 < path fillRule = "evenodd" clipRule = "evenodd" d = "M49.9118 2.02335C52.3173 -0.55232 56.3517 -0.686894 58.9228 1.72277C61.494 4.13244 61.6284 8.17385 59.2229 10.7495L16.4276 56.5729C11.7768 61.552 12.2861 69.5738 17.6453 74.8292L37.4088 94.2091C39.9249 96.6764 39.968 100.72 37.505 103.24C35.042 105.761 31.0056 105.804 28.4895 103.337L8.72593 83.9567C-1.42529 74.0021 -2.43665 58.0741 7.1169 47.8463L49.9118 2.02335Z" fill = "white" > </ path >
5362 </ svg >
5463 </ button >
55- < Navbar />
64+ < Navbar onSearch = { handleSearch } />
5665 < div className = "flex flex-col mx-auto max-w-screen-xl px-2 sm:px-6 lg:px-8" >
5766 < div className = "grid grid-cols-1 gap-4 py-4 " >
5867 < div className = "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" >
5968 {
60- data . map ( data => (
69+ filteredData . map ( data => (
6170 < Stat key = { data . username } data = { data } />
6271 ) )
6372 }
0 commit comments