1
- import React from 'react'
1
+ import React , { useEffect , useState } from 'react'
2
2
import styled from 'styled-components' ;
3
3
import ImageCard from '../components/ImageCard' ;
4
4
import SearchBar from '../components/SearchBar' ;
5
+ import { CircularProgress } from '@mui/material' ;
6
+ import { GetPosts } from '../api' ;
5
7
6
8
const Container = styled . div `
7
9
height:100%;
@@ -68,6 +70,49 @@ gap:20px;
68
70
69
71
function Home ( ) {
70
72
73
+ const [ posts , setPosts ] = useState ( [ ] ) ;
74
+ const [ loading , setLoading ] = useState ( false ) ;
75
+ const [ error , setError ] = useState ( "" ) ;
76
+ const [ search , setSearch ] = useState ( "" ) ;
77
+ const [ filteredPosts , setFilteredPosts ] = useState ( [ ] ) ;
78
+
79
+
80
+ const getPosts = async ( ) => {
81
+ setLoading ( true ) ;
82
+ await GetPosts ( )
83
+ . then ( ( res ) => {
84
+ setLoading ( false ) ;
85
+ setPosts ( res ?. data ?. data ) ;
86
+ setFilteredPosts ( res ?. data ?. data )
87
+ } )
88
+ . catch ( ( error ) => {
89
+ setError ( error ?. response ?. data ?. message ) ;
90
+ setLoading ( false ) ;
91
+
92
+ } )
93
+ }
94
+
95
+ useEffect ( ( ) => {
96
+ getPosts ( ) ;
97
+ } , [ ] )
98
+
99
+ useEffect ( ( ) => {
100
+ if ( ! search ) {
101
+ setFilteredPosts ( posts ) ;
102
+ }
103
+
104
+ const SearchFilteredPosts = posts . filter ( ( post ) => {
105
+ const promptMatch = post ?. prompt ?. toLowerCase ( ) . includes ( search . toString ( ) . toLowerCase ( ) ) ;
106
+ const authorMatch = post ?. name ?. toLowerCase ( ) . includes ( search . toString ( ) . toLowerCase ( ) ) ;
107
+
108
+ return promptMatch || authorMatch ;
109
+ } ) ;
110
+
111
+ if ( search ) {
112
+ setFilteredPosts ( SearchFilteredPosts ) ;
113
+ }
114
+ } , [ posts , search ] )
115
+
71
116
const item = {
72
117
photo : "https://images.pexels.com/photos/26409497/pexels-photo-26409497/free-photo-of-a-small-white-house-sits-in-the-middle-of-a-field.jpeg?auto=compress&cs=tinysrgb&w=400&lazy=load" ,
73
118
author : "Sanjay Rai" ,
@@ -81,14 +126,14 @@ function Home() {
81
126
< Headline > Explore posts in the Community!
82
127
< Span > » Generated with AI « </ Span >
83
128
</ Headline >
84
- < SearchBar > </ SearchBar >
129
+ < SearchBar search = { search } setSearch = { setSearch } > </ SearchBar >
85
130
< Wrapper >
86
- < CardWrapper >
87
- < ImageCard item = { item } > </ ImageCard >
88
- < ImageCard > </ ImageCard >
89
- < ImageCard > </ ImageCard >
90
- < ImageCard > </ ImageCard >
91
- </ CardWrapper >
131
+ { error && < div style = { { color : "red" } } > { error } </ div > }
132
+ { loading ? ( < CircularProgress > </ CircularProgress > ) : (
133
+ < CardWrapper >
134
+ { filteredPosts . length === 0 ? < > No Posts Found </ > : < > { filteredPosts . slice ( ) . reverse ( ) . map ( ( item , index ) => < ImageCard key = { index } item = { item } > </ ImageCard > ) } </ > }
135
+ </ CardWrapper >
136
+ ) }
92
137
</ Wrapper >
93
138
</ Container >
94
139
)
0 commit comments