Query for user bets. Template page to show them.

This commit is contained in:
jahooma 2021-12-13 23:40:38 -06:00
parent 8d7f512248
commit 15691c0a38
3 changed files with 64 additions and 1 deletions

View File

@ -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<Bet[] | 'loading'>('loading')
useEffect(() => {
return listenForUserBets(userId, setBets)
}, [userId])
return bets
}

View File

@ -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)
})
}

29
web/pages/my-bets.tsx Normal file
View File

@ -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 <div />
}
return (
<div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
<Header />
<Col className="w-full md:justify-between md:flex-row mt-4">
{bets.length === 0 ? (
<div>You have not made any bets yet!</div>
) : (
<div>{bets.length}</div>
)}
</Col>
</div>
)
}