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/Guilds.tsx

71 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

import { createContext, useContext, useEffect } 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 { GuildWithDefaultChannelId } from '../models/Guild'
import type { SocketData } from '../tools/handleSocketData'
import { handleSocketData } from '../tools/handleSocketData'
import { GUILDS_CACHE_KEY } from '../tools/cache'
export interface Guilds {
guilds: GuildWithDefaultChannelId[]
hasMore: boolean
nextPage: NextPage
}
const defaultGuildsContext = {} as any
const GuildsContext = createContext<Guilds>(defaultGuildsContext)
2022-05-12 20:35:46 +02:00
export const GuildsProvider: React.FC<React.PropsWithChildren<{}>> = (
props
) => {
const { children } = props
const { authentication } = useAuthentication()
const {
items: guilds,
hasMore,
nextPage,
resetPagination,
setItems
} = usePagination<GuildWithDefaultChannelId>({
api: authentication.api,
url: '/guilds',
cacheKey: GUILDS_CACHE_KEY
})
useEffect(() => {
authentication?.socket?.on(
'guilds',
(data: SocketData<GuildWithDefaultChannelId>) => {
handleSocketData({ data, setItems, cacheKey: GUILDS_CACHE_KEY })
}
)
return () => {
authentication?.socket?.off('guilds')
}
}, [authentication.socket, setItems])
useEffect(() => {
resetPagination()
nextPage()
}, [nextPage, resetPagination])
return (
<GuildsContext.Provider value={{ guilds, hasMore, nextPage }}>
{children}
</GuildsContext.Provider>
)
}
export const useGuilds = (): Guilds => {
const guilds = useContext(GuildsContext)
if (guilds === defaultGuildsContext) {
2022-08-30 21:30:06 +02:00
throw new Error('`useGuilds` must be used within `GuildsProvider`')
}
return guilds
}