2022-01-01 20:42:25 +01:00
|
|
|
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'
|
2022-08-24 17:22:55 +02:00
|
|
|
import { GUILDS_CACHE_KEY } from '../tools/cache'
|
2022-01-01 20:42:25 +01:00
|
|
|
|
|
|
|
export interface Guilds {
|
|
|
|
guilds: GuildWithDefaultChannelId[]
|
|
|
|
hasMore: boolean
|
|
|
|
nextPage: NextPage
|
|
|
|
}
|
|
|
|
|
|
|
|
const defaultGuildsContext = {} as any
|
|
|
|
const GuildsContext = createContext<Guilds>(defaultGuildsContext)
|
|
|
|
|
2023-04-03 00:11:19 +02:00
|
|
|
export const GuildsProvider: React.FC<React.PropsWithChildren> = (props) => {
|
2022-01-01 20:42:25 +01:00
|
|
|
const { children } = props
|
|
|
|
|
|
|
|
const { authentication } = useAuthentication()
|
|
|
|
|
|
|
|
const {
|
|
|
|
items: guilds,
|
|
|
|
hasMore,
|
|
|
|
nextPage,
|
2022-03-05 18:22:30 +01:00
|
|
|
resetPagination,
|
|
|
|
setItems
|
2022-01-01 20:42:25 +01:00
|
|
|
} = usePagination<GuildWithDefaultChannelId>({
|
|
|
|
api: authentication.api,
|
2022-08-24 17:22:55 +02:00
|
|
|
url: '/guilds',
|
|
|
|
cacheKey: GUILDS_CACHE_KEY
|
2022-01-01 20:42:25 +01:00
|
|
|
})
|
|
|
|
|
2022-03-05 18:22:30 +01:00
|
|
|
useEffect(() => {
|
2022-08-24 17:22:55 +02:00
|
|
|
authentication?.socket?.on(
|
2022-03-05 18:22:30 +01:00
|
|
|
'guilds',
|
|
|
|
(data: SocketData<GuildWithDefaultChannelId>) => {
|
2022-08-24 17:22:55 +02:00
|
|
|
handleSocketData({ data, setItems, cacheKey: GUILDS_CACHE_KEY })
|
2022-03-05 18:22:30 +01:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
return () => {
|
2022-08-24 17:22:55 +02:00
|
|
|
authentication?.socket?.off('guilds')
|
2022-03-05 18:22:30 +01:00
|
|
|
}
|
|
|
|
}, [authentication.socket, setItems])
|
|
|
|
|
2022-01-01 20:42:25 +01:00
|
|
|
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`')
|
2022-01-01 20:42:25 +01:00
|
|
|
}
|
|
|
|
return guilds
|
|
|
|
}
|