From 63b7f64683f9c35b76af6d82d9d52753e949f18d Mon Sep 17 00:00:00 2001 From: James Grugett Date: Sun, 6 Feb 2022 16:55:14 -0600 Subject: [PATCH] Listen for folds in contract page --- web/hooks/use-fold.ts | 11 +++++++++++ web/lib/firebase/folds.ts | 18 ++++++++++++++++++ web/pages/[username]/[contractSlug].tsx | 5 ++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/web/hooks/use-fold.ts b/web/hooks/use-fold.ts index 010b7217..2bbe6e23 100644 --- a/web/hooks/use-fold.ts +++ b/web/hooks/use-fold.ts @@ -5,6 +5,7 @@ import { getFollowedFolds, listenForFold, listenForFolds, + listenForFoldsWithTags, listenForFollow, } from '../lib/firebase/folds' @@ -28,6 +29,16 @@ export const useFolds = () => { return folds } +export const useFoldsWithTags = (tags: string[] | undefined) => { + const [folds, setFolds] = useState() + + useEffect(() => { + if (tags && tags.length > 0) return listenForFoldsWithTags(tags, setFolds) + }, [tags]) + + return folds +} + export const useFollowingFold = (fold: Fold, user: User | null | undefined) => { const [following, setFollowing] = useState() diff --git a/web/lib/firebase/folds.ts b/web/lib/firebase/folds.ts index 58618414..c5a70a2c 100644 --- a/web/lib/firebase/folds.ts +++ b/web/lib/firebase/folds.ts @@ -154,6 +154,24 @@ export async function getFoldsByTags(tags: string[]) { return _.sortBy(folds, (fold) => -1 * fold.followCount) } +export function listenForFoldsWithTags( + tags: string[], + setFolds: (folds: Fold[]) => void +) { + const lowercaseTags = tags.map((tag) => tag.toLowerCase()) + const q = + // TODO: split into multiple queries if tags.length > 10. + query( + foldCollection, + where('lowercaseTags', 'array-contains-any', lowercaseTags) + ) + + return listenForValues(q, (folds) => { + const sorted = _.sortBy(folds, (fold) => -1 * fold.followCount) + setFolds(sorted) + }) +} + export async function getFollowedFolds(userId: string) { const snapshot = await getDocs( query(collectionGroup(db, 'followers'), where('userId', '==', userId)) diff --git a/web/pages/[username]/[contractSlug].tsx b/web/pages/[username]/[contractSlug].tsx index 6cd03df0..f239253d 100644 --- a/web/pages/[username]/[contractSlug].tsx +++ b/web/pages/[username]/[contractSlug].tsx @@ -25,6 +25,7 @@ import { Comment, listAllComments } from '../../lib/firebase/comments' import Custom404 from '../404' import { getFoldsByTags } from '../../lib/firebase/folds' import { Fold } from '../../../common/fold' +import { useFoldsWithTags } from '../../hooks/use-fold' export async function getStaticProps(props: { params: { username: string; contractSlug: string } @@ -71,7 +72,9 @@ export default function ContractPage(props: { const user = useUser() const contract = useContractWithPreload(props.slug, props.contract) - const { bets, comments, folds } = props + const { bets, comments } = props + + const folds = useFoldsWithTags(contract?.tags) ?? props.folds if (!contract) { return