Skip to content

Commit 357b60e

Browse files
committed
feat: cache parsed InitialState results to Map for later use
1 parent a7d4fa6 commit 357b60e

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

lib/index.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,22 @@
33
* SPDX-License-Identifier: GPL-3.0-or-later
44
*/
55

6+
const cachedInitialState = new Map<string, unknown>()
7+
68
/**
79
* @param app app ID, e.g. "mail"
810
* @param key name of the property
911
* @param fallback optional parameter to use as default value
1012
* @throws if the key can't be found
1113
*/
1214
export function loadState<T>(app: string, key: string, fallback?: T): T {
13-
const elem = <HTMLInputElement>document.querySelector(`#initial-state-${app}-${key}`)
15+
const selector = `#initial-state-${app}-${key}`
16+
if (cachedInitialState.has(selector)) {
17+
return cachedInitialState.get(selector) as T
18+
}
19+
20+
const elem = document.querySelector<HTMLInputElement>(selector)
21+
1422
if (elem === null) {
1523
if (fallback !== undefined) {
1624
return fallback
@@ -19,7 +27,9 @@ export function loadState<T>(app: string, key: string, fallback?: T): T {
1927
}
2028

2129
try {
22-
return JSON.parse(atob(elem.value))
30+
const parsedValue = JSON.parse(atob(elem.value))
31+
cachedInitialState.set(selector, parsedValue)
32+
return parsedValue
2333
} catch (e) {
2434
throw new Error(`Could not parse initial state ${key} of ${app}`)
2535
}

0 commit comments

Comments
 (0)