amanpay / web /src /hooks /useD2Session.ts
MHamdan's picture
CI deploy 59e9772
dc47d57 verified
Raw
History Blame Contribute Delete
719 Bytes
import { useEffect, useState } from 'react'
import { getD2Account, getD2Csrf, onD2Change, type D2Account } from '../api/identity'
interface D2SessionState {
account: D2Account | null
csrf: string | null
authed: boolean
isOperator: boolean
}
function snapshot(): D2SessionState {
const account = getD2Account()
return {
account,
csrf: getD2Csrf(),
authed: account !== null,
isOperator: account?.role === 'operator',
}
}
/** Subscribes to the in-memory D2 account/csrf store (api/identity.ts). */
export function useD2Session(): D2SessionState {
const [state, setState] = useState<D2SessionState>(snapshot)
useEffect(() => onD2Change(() => setState(snapshot())), [])
return state
}