2022-08-30 12:39:10 +00:00
|
|
|
import { useEffect, useState } from 'react'
|
2022-10-06 23:50:53 +00:00
|
|
|
import { DateDoc, Post } from 'common/post'
|
2022-10-12 14:04:39 +00:00
|
|
|
import {
|
|
|
|
getAllPosts,
|
|
|
|
listenForDateDocs,
|
|
|
|
listenForPost,
|
|
|
|
} from 'web/lib/firebase/posts'
|
2022-08-30 12:39:10 +00:00
|
|
|
|
|
|
|
export const usePost = (postId: string | undefined) => {
|
|
|
|
const [post, setPost] = useState<Post | null | undefined>()
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (postId) return listenForPost(postId, setPost)
|
|
|
|
}, [postId])
|
|
|
|
|
|
|
|
return post
|
|
|
|
}
|
2022-09-23 19:11:50 +00:00
|
|
|
|
|
|
|
export const usePosts = (postIds: string[]) => {
|
|
|
|
const [posts, setPosts] = useState<Post[]>([])
|
|
|
|
useEffect(() => {
|
|
|
|
if (postIds.length === 0) return
|
|
|
|
setPosts([])
|
|
|
|
|
|
|
|
const unsubscribes = postIds.map((postId) =>
|
|
|
|
listenForPost(postId, (post) => {
|
|
|
|
if (post) {
|
|
|
|
setPosts((posts) => [...posts, post])
|
|
|
|
}
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
unsubscribes.forEach((unsubscribe) => unsubscribe())
|
|
|
|
}
|
|
|
|
}, [postIds])
|
|
|
|
|
|
|
|
return posts
|
|
|
|
.filter(
|
|
|
|
(post, index, self) => index === self.findIndex((t) => t.id === post.id)
|
|
|
|
)
|
|
|
|
.sort((a, b) => b.createdTime - a.createdTime)
|
|
|
|
}
|
2022-10-06 23:50:53 +00:00
|
|
|
|
2022-10-12 14:04:39 +00:00
|
|
|
export const useAllPosts = () => {
|
|
|
|
const [posts, setPosts] = useState<Post[]>([])
|
|
|
|
useEffect(() => {
|
|
|
|
getAllPosts().then(setPosts)
|
|
|
|
}, [])
|
|
|
|
return posts
|
|
|
|
}
|
|
|
|
|
2022-10-06 23:50:53 +00:00
|
|
|
export const useDateDocs = () => {
|
|
|
|
const [dateDocs, setDateDocs] = useState<DateDoc[]>()
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
return listenForDateDocs(setDateDocs)
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
return dateDocs
|
|
|
|
}
|