diff options
author | Sebastian <sebasjm@gmail.com> | 2023-05-19 13:24:30 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2023-05-19 13:24:30 -0300 |
commit | 35cc13e229ddc4953a1e68b6b7ea18c54eb9a70b (patch) | |
tree | fc2b54d8a148396676fc01e8a3b8332ea6b79216 /packages/web-util/src/hooks/useNotifications.ts | |
parent | 38c65cc84ad0b41ccccf479fd55d0df21f0afe86 (diff) | |
download | wallet-core-35cc13e229ddc4953a1e68b6b7ea18c54eb9a70b.tar.xz |
imported useNotifications, new memory storage hook and fixed but in localstorage
Diffstat (limited to 'packages/web-util/src/hooks/useNotifications.ts')
-rw-r--r-- | packages/web-util/src/hooks/useNotifications.ts | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/packages/web-util/src/hooks/useNotifications.ts b/packages/web-util/src/hooks/useNotifications.ts new file mode 100644 index 000000000..deaa7a7c1 --- /dev/null +++ b/packages/web-util/src/hooks/useNotifications.ts @@ -0,0 +1,67 @@ +import { TranslatedString } from "@gnu-taler/taler-util"; +import { StateUpdater, useEffect, useState } from "preact/hooks"; +import { memoryMap } from "../index.browser.js"; + +export type NotificationMessage = ErrorNotification | InfoNotification; + +interface ErrorNotification { + type: "error"; + title: TranslatedString; + description?: TranslatedString; + debug?: string; +} +interface InfoNotification { + type: "info"; + title: TranslatedString; +} + +const storage = memoryMap<NotificationMessage[]>(); +const NOTIFICATION_KEY = "notification"; + +export function notifyError( + title: TranslatedString, + description: TranslatedString | undefined, + debug?: any, +) { + const currentState: NotificationMessage[] = + storage.get(NOTIFICATION_KEY) ?? []; + const newState = currentState.concat({ + type: "error", + title, + description, + debug, + }); + storage.set(NOTIFICATION_KEY, newState); +} +export function notifyInfo(title: TranslatedString) { + const currentState: NotificationMessage[] = + storage.get(NOTIFICATION_KEY) ?? []; + const newState = currentState.concat({ type: "info", title }); + storage.set(NOTIFICATION_KEY, newState); +} + +type Notification = { + message: NotificationMessage; + remove: () => void; +}; + +export function useNotifications(): Notification[] { + const [value, setter] = useState<NotificationMessage[]>([]); + useEffect(() => { + return storage.onUpdate(NOTIFICATION_KEY, () => { + const mem = storage.get(NOTIFICATION_KEY) ?? []; + setter(mem); + }); + }); + return value.map((message, idx) => { + return { + message, + remove: () => { + const mem = storage.get(NOTIFICATION_KEY) ?? []; + const newState = Array.from(mem); + newState.splice(idx, 1); + storage.set(NOTIFICATION_KEY, newState); + }, + }; + }); +} |