From 15691c0a38b1c2758da3b6026ff84408a00c323f Mon Sep 17 00:00:00 2001 From: jahooma Date: Mon, 13 Dec 2021 23:40:38 -0600 Subject: [PATCH] Query for user bets. Template page to show them. --- web/hooks/use-user-bets.ts | 12 ++++++++++++ web/lib/firebase/bets.ts | 24 +++++++++++++++++++++++- web/pages/my-bets.tsx | 29 +++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 web/hooks/use-user-bets.ts create mode 100644 web/pages/my-bets.tsx diff --git a/web/hooks/use-user-bets.ts b/web/hooks/use-user-bets.ts new file mode 100644 index 00000000..e52d3786 --- /dev/null +++ b/web/hooks/use-user-bets.ts @@ -0,0 +1,12 @@ +import { useEffect, useState } from 'react' +import { Bet, listenForUserBets } from '../lib/firebase/bets' + +export const useUserBets = (userId: string) => { + const [bets, setBets] = useState('loading') + + useEffect(() => { + return listenForUserBets(userId, setBets) + }, [userId]) + + return bets +} diff --git a/web/lib/firebase/bets.ts b/web/lib/firebase/bets.ts index 79036c44..92b33010 100644 --- a/web/lib/firebase/bets.ts +++ b/web/lib/firebase/bets.ts @@ -1,4 +1,10 @@ -import { collection, onSnapshot } from 'firebase/firestore' +import { + collection, + collectionGroup, + query, + onSnapshot, + where, +} from 'firebase/firestore' import { db } from './init' export type Bet = { @@ -30,3 +36,19 @@ export function listenForBets( setBets(bets) }) } + +export function listenForUserBets( + userId: string, + setBets: (bets: Bet[]) => void +) { + const userQuery = query( + collectionGroup(db, 'bets'), + where('userId', '==', userId) + ) + + return onSnapshot(userQuery, (snap) => { + const bets = snap.docs.map((doc) => doc.data() as Bet) + bets.sort((bet1, bet2) => bet1.createdTime - bet2.createdTime) + setBets(bets) + }) +} diff --git a/web/pages/my-bets.tsx b/web/pages/my-bets.tsx new file mode 100644 index 00000000..167565e8 --- /dev/null +++ b/web/pages/my-bets.tsx @@ -0,0 +1,29 @@ +import React from 'react' +import { Header } from '../components/header' +import { Col } from '../components/layout/col' +import { useUser } from '../hooks/use-user' +import { useUserBets } from '../hooks/use-user-bets' + +export default function MyBets() { + const user = useUser() + + const bets = useUserBets(user?.id ?? '') + + if (bets === 'loading') { + return
+ } + + return ( +
+
+ + + {bets.length === 0 ? ( +
You have not made any bets yet!
+ ) : ( +
{bets.length}
+ )} + +
+ ) +}