This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/contexts/Members.tsx

101 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-08-30 21:30:06 +02:00
import { createContext, useContext, useEffect, useMemo } from 'react'
2022-08-31 21:44:33 +02:00
import type { NextPage } from '../hooks/usePagination'
import { usePagination } from '../hooks/usePagination'
2022-03-16 12:18:09 +01:00
import { useAuthentication } from '../tools/authentication'
2022-08-31 21:44:33 +02:00
import type { MemberWithPublicUser } from '../models/Member'
import type { GuildsChannelsPath } from '../components/Application'
import type { SocketData } from '../tools/handleSocketData'
import { handleSocketData } from '../tools/handleSocketData'
import type { User } from '../models/User'
import type { CacheKey } from '../tools/cache'
import { MEMBERS_CACHE_KEY } from '../tools/cache'
export interface Members {
members: MemberWithPublicUser[]
hasMore: boolean
nextPage: NextPage
}
const defaultMembersContext = {} as any
const MembersContext = createContext<Members>(defaultMembersContext)
export interface MembersProviderProps {
path: GuildsChannelsPath
}
2022-05-12 20:35:46 +02:00
export const MembersProviders: React.FC<
React.PropsWithChildren<MembersProviderProps>
> = (props) => {
const { children, path } = props
const { authentication } = useAuthentication()
2022-08-30 21:30:06 +02:00
const cacheKey = useMemo<CacheKey>(() => {
return `${path.guildId}-${MEMBERS_CACHE_KEY}`
}, [path.guildId])
const {
items: members,
hasMore,
nextPage,
resetPagination,
setItems
} = usePagination<MemberWithPublicUser>({
api: authentication.api,
url: `/guilds/${path.guildId}/members`,
cacheKey
})
useEffect(() => {
authentication?.socket?.on(
'members',
(data: SocketData<MemberWithPublicUser>) => {
handleSocketData({ data, setItems, cacheKey })
}
)
authentication?.socket?.on('users', (data: SocketData<User>) => {
setItems((oldItems) => {
const newItems = [...oldItems]
switch (data.action) {
case 'update': {
for (const member of newItems) {
if (member.user.id === data.item.id) {
member.user = data.item
break
}
}
break
}
}
return newItems
})
})
return () => {
authentication?.socket?.off('members')
authentication?.socket?.off('users')
}
}, [authentication.socket, setItems, cacheKey])
useEffect(() => {
resetPagination()
nextPage()
}, [nextPage, resetPagination])
return (
<MembersContext.Provider value={{ members, hasMore, nextPage }}>
{children}
</MembersContext.Provider>
)
}
export const useMembers = (): Members => {
const members = useContext(MembersContext)
if (members === defaultMembersContext) {
2022-08-30 21:30:06 +02:00
throw new Error('`useMembers` must be used within `MembersProvider`')
}
return members
}