2021-12-17 04:17:33 +00:00
|
|
|
import { useEffect, useState } from 'react'
|
2022-06-08 03:24:18 +00:00
|
|
|
import { useFirestoreDocumentData } from '@react-query-firebase/firestore'
|
|
|
|
import { QueryClient } from 'react-query'
|
|
|
|
|
|
|
|
import { DocumentData } from 'firebase/firestore'
|
2022-05-09 13:04:36 +00:00
|
|
|
import { PrivateUser } from 'common/user'
|
2022-02-04 03:04:56 +00:00
|
|
|
import {
|
2022-06-08 04:06:14 +00:00
|
|
|
getUser,
|
2022-02-04 03:04:56 +00:00
|
|
|
listenForLogin,
|
|
|
|
listenForPrivateUser,
|
|
|
|
listenForUser,
|
|
|
|
User,
|
2022-06-08 03:24:18 +00:00
|
|
|
userDocRef,
|
2022-05-09 13:04:36 +00:00
|
|
|
} from 'web/lib/firebase/users'
|
2022-04-06 18:55:59 +00:00
|
|
|
import { useStateCheckEquality } from './use-state-check-equality'
|
2022-06-14 16:54:58 +00:00
|
|
|
import { identifyUser } from 'web/lib/service/analytics'
|
2021-12-09 22:05:55 +00:00
|
|
|
|
|
|
|
export const useUser = () => {
|
2022-04-06 18:55:59 +00:00
|
|
|
const [user, setUser] = useStateCheckEquality<User | null | undefined>(
|
|
|
|
undefined
|
|
|
|
)
|
2021-12-17 04:09:38 +00:00
|
|
|
|
2022-04-06 18:55:59 +00:00
|
|
|
useEffect(() => listenForLogin(setUser), [setUser])
|
2021-12-15 00:45:13 +00:00
|
|
|
|
|
|
|
const userId = user?.id
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-06-14 16:54:58 +00:00
|
|
|
if (userId) {
|
|
|
|
identifyUser(userId)
|
|
|
|
return listenForUser(userId, setUser)
|
|
|
|
}
|
2022-04-06 18:55:59 +00:00
|
|
|
}, [userId, setUser])
|
2021-12-15 00:45:13 +00:00
|
|
|
|
2021-12-09 23:23:21 +00:00
|
|
|
return user
|
|
|
|
}
|
2022-02-04 03:04:56 +00:00
|
|
|
|
|
|
|
export const usePrivateUser = (userId?: string) => {
|
|
|
|
const [privateUser, setPrivateUser] = useState<
|
|
|
|
PrivateUser | null | undefined
|
|
|
|
>(undefined)
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (userId) return listenForPrivateUser(userId, setPrivateUser)
|
|
|
|
}, [userId])
|
|
|
|
|
|
|
|
return privateUser
|
|
|
|
}
|
2022-06-08 03:24:18 +00:00
|
|
|
|
|
|
|
export const useUserById = (userId: string) => {
|
|
|
|
const result = useFirestoreDocumentData<DocumentData, User>(
|
|
|
|
['users', userId],
|
|
|
|
userDocRef(userId),
|
|
|
|
{ subscribe: true, includeMetadataChanges: true }
|
|
|
|
)
|
|
|
|
|
|
|
|
return result.isLoading ? undefined : result.data
|
|
|
|
}
|
|
|
|
|
|
|
|
const queryClient = new QueryClient()
|
|
|
|
|
|
|
|
export const prefetchUser = (userId: string) => {
|
2022-06-08 04:06:14 +00:00
|
|
|
queryClient.prefetchQuery(['users', userId], () => getUser(userId))
|
2022-06-08 03:24:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const prefetchUsers = (userIds: string[]) => {
|
2022-06-08 04:06:14 +00:00
|
|
|
userIds.forEach(prefetchUser)
|
2022-06-08 03:24:18 +00:00
|
|
|
}
|