Skip to content

Commit bd26493

Browse files
fix localstorge values not reading on navigation to another app
1 parent 09f6c22 commit bd26493

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

client/packages/lowcoder/src/comps/hooks/localStorageComp.ts

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { isEmpty } from "lodash";
33
import { simpleMultiComp, stateComp, withViewFn } from "../generators";
44
import { NameConfig, withExposingConfigs } from "../generators/withExposing";
55
import { JSONObject } from "../../util/jsonTypes";
6-
import { useEffect } from "react";
6+
import { useEffect, useMemo, useCallback } from "react";
77
import isEqual from "fast-deep-equal";
88
import { trans } from "i18n";
99
import log from "loglevel";
@@ -13,28 +13,36 @@ const APP_STORE_NAMESPACE = "lowcoder_app_local_storage";
1313
const LocalStorageCompBase = withViewFn(
1414
simpleMultiComp({ values: stateComp<JSONObject>({}) }),
1515
(comp) => {
16-
// add custom event listener to update values reactively
17-
useEffect(() => {
18-
const handler = () => {
19-
try {
20-
const raw = localStorage.getItem(APP_STORE_NAMESPACE) || "{}";
21-
const parsed = JSON.parse(raw);
22-
comp.children.values.dispatchChangeValueAction(parsed);
23-
} catch (e) {
24-
log.error("Failed to parse localStorage:", e);
25-
}
26-
};
16+
const originStore = localStorage.getItem(APP_STORE_NAMESPACE) || "{}";
17+
18+
const parseStore = useMemo(() => {
19+
try {
20+
return JSON.parse(originStore);
21+
} catch (e) {
22+
log.error("application local storage invalid");
23+
return {};
24+
}
25+
}, [originStore]);
26+
27+
const handleStorageUpdate = useCallback(() => {
28+
try {
29+
comp.children.values.dispatchChangeValueAction(parseStore);
30+
} catch (e) {
31+
log.error("Failed to parse localStorage:", e);
32+
}
33+
}, [parseStore, comp.children.values]);
2734

35+
useEffect(() => {
2836
// Add listener on mount
29-
window.addEventListener("lowcoder-localstorage-updated", handler);
37+
window.addEventListener("lowcoder-localstorage-updated", handleStorageUpdate);
3038

3139
// Run once on mount to initialize
32-
handler();
40+
handleStorageUpdate();
3341

3442
return () => {
35-
window.removeEventListener("lowcoder-localstorage-updated", handler);
43+
window.removeEventListener("lowcoder-localstorage-updated", handleStorageUpdate);
3644
};
37-
}, []);
45+
}, [handleStorageUpdate]);
3846

3947
return null;
4048
}

0 commit comments

Comments
 (0)