2022-01-01 20:42:25 +01:00
|
|
|
import { createContext, useContext, useEffect } from 'react'
|
|
|
|
|
2022-03-16 12:18:09 +01:00
|
|
|
import { NextPage, usePagination } from '../hooks/usePagination'
|
|
|
|
import { useAuthentication } from '../tools/authentication'
|
|
|
|
import { GuildWithDefaultChannelId } from '../models/Guild'
|
|
|
|
import { handleSocketData, SocketData } 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)
|
|
|
|
|
2022-05-12 20:35:46 +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
|
|
|
|
}
|