manifold/web/hooks/use-users.ts

67 lines
1.6 KiB
TypeScript
Raw Normal View History

import { useState, useEffect } from 'react'
import { PrivateUser, User } from 'common/user'
import {
getUser,
listenForAllUsers,
listenForPrivateUsers,
} from 'web/lib/firebase/users'
import { groupBy, sortBy, difference } from 'lodash'
import { getContractsOfUserBets } from 'web/lib/firebase/bets'
import { useFollows } from './use-follows'
export const useUsers = () => {
const [users, setUsers] = useState<User[]>([])
useEffect(() => {
listenForAllUsers(setUsers)
}, [])
return users
}
2022-01-24 06:48:06 +00:00
2022-03-21 22:19:42 +00:00
export const useUserById = (userId?: string) => {
const [user, setUser] = useState<User | undefined>(undefined)
useEffect(() => {
2022-03-21 22:19:42 +00:00
if (userId) {
getUser(userId).then(setUser)
}
}, [userId])
return user
}
2022-01-24 06:48:06 +00:00
export const usePrivateUsers = () => {
const [users, setUsers] = useState<PrivateUser[]>([])
useEffect(() => {
listenForPrivateUsers(setUsers)
}, [])
return users
}
export const useDiscoverUsers = (userId: string | null | undefined) => {
const [discoverUserIds, setDiscoverUserIds] = useState<string[]>([])
useEffect(() => {
if (userId)
getContractsOfUserBets(userId).then((contracts) => {
const creatorCounts = Object.entries(
groupBy(contracts, 'creatorId')
).map(([id, contracts]) => [id, contracts.length] as const)
const topCreatorIds = sortBy(creatorCounts, ([_, i]) => i)
.map(([id]) => id)
.reverse()
setDiscoverUserIds(topCreatorIds)
})
}, [userId])
const followedUserIds = useFollows(userId)
const nonSuggestions = [userId ?? '', ...(followedUserIds ?? [])]
return difference(discoverUserIds, nonSuggestions).slice(0, 50)
}