home.tsx
1 import React, { useEffect } from "react"; 2 import { BlogData } from "./BlogData"; 3 import { Link } from "wouter"; 4 import { NavBar } from "./navbar"; 5 6 7 interface HomeProps { 8 blogData: BlogData 9 } 10 11 function Home(props: HomeProps) { 12 13 const [name, setName] = React.useState("loading") 14 const [posts, setPosts] = React.useState<any>([]) 15 16 const { blogData } = props; 17 18 useEffect(() => { 19 (async () => { 20 const _name = await blogData.getName() 21 setName(_name) 22 })() 23 },[]) 24 25 useEffect(() => { 26 (async () => { 27 const _posts = await blogData.getPosts() 28 setPosts(_posts) 29 })() 30 },[]) 31 32 useEffect(() => { 33 setInterval(async () => { 34 await blogData.refreshContentFromIPFS() 35 const _posts = await blogData.getPosts() 36 setPosts(_posts) 37 }, 5000) 38 }, [setPosts]) 39 40 const postElements = posts.map((post: any) => { 41 function title() { 42 function shorten(str: string) { 43 if (str.length < 50) return str; 44 45 return str.slice(0, 50) + "..." 46 } 47 48 if (post.title) return post.title 49 else { 50 return shorten(post.content) 51 } 52 } 53 54 return ( 55 <Link href={`/posts/${post.id}`}> 56 <li key={post.id}>{title()} {post.created_at}</li> 57 </Link> 58 ) 59 }) 60 61 62 return (<div> 63 <h1>{name}</h1> 64 <h2>Posts</h2> 65 <div> 66 <ul> 67 {postElements} 68 </ul> 69 </div> 70 <NavBar /> 71 </div>) 72 } 73 74 export { Home }