From be4a9758d5a5c54a1b5ddc9994460a3f839865b3 Mon Sep 17 00:00:00 2001 From: MrWindlike Date: Tue, 15 Mar 2022 15:26:43 +0800 Subject: [PATCH] feat: add `setValue` method to localStorage trait --- .../runtime/src/traits/core/LocalStorage.tsx | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/runtime/src/traits/core/LocalStorage.tsx b/packages/runtime/src/traits/core/LocalStorage.tsx index bada93ab..40c76368 100644 --- a/packages/runtime/src/traits/core/LocalStorage.tsx +++ b/packages/runtime/src/traits/core/LocalStorage.tsx @@ -24,24 +24,33 @@ const LocalStorageTraitFactory: TraitImplFactory> = ( const HasInitializedMap = new Map(); const PrevValueCache: Record = {}; - return ({ key, value, componentId, mergeState }) => { + return ({ key, value, componentId, mergeState, subscribeMethods }) => { const hashId = `#${componentId}@${key}`; const hasInitialized = HasInitializedMap.get(hashId); + const setValue = (newValue: any) => { + PrevValueCache[key] = newValue; + mergeState({ + [key]: newValue, + }); + localStorage.setItem(hashId, JSON.stringify(newValue)); + }; + if (key) { if (!hasInitialized) { PrevValueCache[key] = getLocalStorageValue(hashId); mergeState({ [key]: PrevValueCache[key], }); + subscribeMethods({ + setValue: ({ value: newValue }: { value: any }) => { + setValue(newValue); + }, + }); HasInitializedMap.set(hashId, true); } else { if (!isEqual(PrevValueCache[key], value)) { - PrevValueCache[key] = value; - mergeState({ - [key]: value, - }); - localStorage.setItem(hashId, JSON.stringify(value)); + setValue(value); } } } @@ -62,7 +71,14 @@ export default { spec: { properties: PropsSchema, state: Type.Object({}), - methods: [], + methods: [ + { + name: 'setValue', + parameters: Type.Object({ + value: Type.Any(), + }), + }, + ], }, }), factory: LocalStorageTraitFactory,