diff options
Diffstat (limited to 'packages/demobank-ui/src/hooks')
-rw-r--r-- | packages/demobank-ui/src/hooks/backend.ts | 60 |
1 files changed, 41 insertions, 19 deletions
diff --git a/packages/demobank-ui/src/hooks/backend.ts b/packages/demobank-ui/src/hooks/backend.ts index 3b00edee3..967d5ee85 100644 --- a/packages/demobank-ui/src/hooks/backend.ts +++ b/packages/demobank-ui/src/hooks/backend.ts @@ -1,33 +1,55 @@ import { hooks } from "@gnu-taler/web-util/lib/index.browser"; -import { StateUpdater } from "preact/hooks"; /** * Has the information to reach and * authenticate at the bank's backend. */ -export interface BackendStateType { - url?: string; - username?: string; - password?: string; +export type BackendState = LoggedIn | LoggedOut + +export interface BackendInfo { + url: string; + username: string; + password: string; +} + +interface LoggedIn extends BackendInfo { + status: "loggedIn" +} +interface LoggedOut { + status: "loggedOut" } +export const defaultState: BackendState = { status: "loggedOut" } + +export interface BackendStateHandler { + state: BackendState, + clear(): void; + save(info: BackendInfo): void; +} /** * Return getters and setters for * login credentials and backend's * base URL. */ -type BackendStateTypeOpt = BackendStateType | undefined; -export function useBackendState( - state?: BackendStateType, -): [BackendStateTypeOpt, StateUpdater<BackendStateTypeOpt>] { - const ret = hooks.useLocalStorage("backend-state", JSON.stringify(state)); - const retObj: BackendStateTypeOpt = ret[0] ? JSON.parse(ret[0]) : ret[0]; - const retSetter: StateUpdater<BackendStateTypeOpt> = function (val) { - const newVal = - val instanceof Function - ? JSON.stringify(val(retObj)) - : JSON.stringify(val); - ret[1](newVal); - }; - return [retObj, retSetter]; +export function useBackendState(): BackendStateHandler { + const [value, update] = hooks.useLocalStorage("backend-state", JSON.stringify(defaultState)); + // const parsed = value !== undefined ? JSON.parse(value) : value; + let parsed + try { + parsed = JSON.parse(value!) + } catch { + parsed = undefined + } + const state: BackendState = !parsed?.status ? defaultState : parsed + + return { + state, + clear() { + update(JSON.stringify(defaultState)) + }, + save(info) { + const nextState: BackendState = { status: "loggedIn", ...info } + update(JSON.stringify(nextState)) + }, + } } |