Skip to content

Commit

Permalink
refactor(react-identity): merge internal state
Browse files Browse the repository at this point in the history
  • Loading branch information
matej21 committed Feb 26, 2024
1 parent abebdc2 commit 7acd949
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions packages/react-identity/src/hooks/useFetchIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,50 @@ import { useSessionToken } from '@contember/react-client'
import { useFetchMe } from '../internal/hooks/useFetchMe'
import { useLogoutInternal } from '../internal/hooks/useLogoutInternal'

export const useFetchIdentity = (): [{ state: IdentityStateValue, identity: Identity | undefined }, IdentityMethods] => {
export type IdentityState = { state: IdentityStateValue, identity: Identity | undefined }
export const useFetchIdentity = (): [IdentityState, IdentityMethods] => {
const sessionToken = useSessionToken()
const fetchMe = useFetchMe()

const [identityState, setIdentityState] = useState<IdentityStateValue>(sessionToken ? 'loading' : 'none')
const [identity, setIdentity] = useState<Identity | undefined>()
const [identityState, setIdentityState] = useState<IdentityState>({ state: sessionToken ? 'loading' : 'none', identity: undefined })

const clearIdentity = useCallback(() => setIdentityState('cleared'), [])
const clearIdentity = useCallback(() => setIdentityState({ state: 'cleared', identity: undefined }), [])
const logout = useLogoutInternal(clearIdentity)

const fetch = useCallback(async () => {
setIdentityState('loading')
setIdentityState({ state: 'loading', identity: undefined })
try {
const response = await fetchMe()
const person = response.person
const projects = response.projects
const permissions = response.permissions ?? { canCreateProject: false }

setIdentityState('success')
setIdentity({
id: response.id,
person: person ?? undefined,
projects: projects.map(it => ({
name: it.project.name,
slug: it.project.slug,
roles: it.memberships.map(it => it.role),
})),
permissions,
setIdentityState({
state: 'success',
identity: {
id: response.id,
person: person ?? undefined,
projects: projects.map(it => ({
name: it.project.name,
slug: it.project.slug,
roles: it.memberships.map(it => it.role),
})),
permissions,
},
})
} catch (e) {
console.error(e)
if (typeof e === 'object' && e !== null && 'status' in e && (e as { status?: unknown }).status === 401) {
logout({ noRedirect: true })
setIdentityState('cleared')
setIdentityState({ state: 'cleared', identity: undefined })
} else {
setIdentityState('failed')
setIdentityState({ state: 'failed', identity: undefined })
}
}
}, [fetchMe, logout])

return [
{ state: identityState, identity },
identityState,
useMemo((): IdentityMethods => ({
clearIdentity,
refreshIdentity: fetch,
Expand Down

0 comments on commit 7acd949

Please sign in to comment.