2023-11-20 15:04:38 +00:00
|
|
|
import React, { useContext } from 'react'
|
2021-11-28 17:29:17 +00:00
|
|
|
import { useQuery } from '@apollo/client'
|
|
|
|
import { ME } from '../fragments/users'
|
2023-07-31 19:54:30 +00:00
|
|
|
import { SSR } from '../lib/constants'
|
2021-05-25 00:08:56 +00:00
|
|
|
|
|
|
|
export const MeContext = React.createContext({
|
|
|
|
me: null
|
|
|
|
})
|
|
|
|
|
2021-11-28 17:29:17 +00:00
|
|
|
export function MeProvider ({ me, children }) {
|
2023-11-17 04:00:53 +00:00
|
|
|
const { data, refetch } = useQuery(ME, SSR ? {} : { pollInterval: 1000, nextFetchPolicy: 'cache-and-network' })
|
2023-11-20 23:43:26 +00:00
|
|
|
// this makes sure that we always use the fetched data if it's null.
|
|
|
|
// without this, we would always fallback to the `me` object
|
|
|
|
// which was passed during page load which (visually) breaks switching to anon
|
|
|
|
const futureMe = data?.me ?? (data?.me === null ? null : me)
|
2021-05-25 00:08:56 +00:00
|
|
|
|
|
|
|
return (
|
2023-12-05 00:43:40 +00:00
|
|
|
<MeContext.Provider value={{ me: futureMe, refreshMe: refetch }}>
|
2021-05-25 00:08:56 +00:00
|
|
|
{children}
|
|
|
|
</MeContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useMe () {
|
2023-12-05 00:43:40 +00:00
|
|
|
return useContext(MeContext)
|
2021-05-25 00:08:56 +00:00
|
|
|
}
|