From 7fd170994ae87062fefa6f9c2fd7968a9376b421 Mon Sep 17 00:00:00 2001 From: KaiyiWing Date: Sat, 13 May 2023 12:46:51 +0800 Subject: [PATCH] feat: polish code --- src/store/atomForConfig.ts | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/store/atomForConfig.ts b/src/store/atomForConfig.ts index 65bcd301..9afa7e6b 100644 --- a/src/store/atomForConfig.ts +++ b/src/store/atomForConfig.ts @@ -12,15 +12,32 @@ export default function atomForConfig>( return atom((get) => { // Get the underlying object const config = get(storageAtom) - // Check if there are missing properties - let hasMissingProperty = false - for (const key in defaultValue) { - if (!(key in config)) { - hasMissingProperty = true - break + + let newConfig: T + + // Check if the types are different + const isTypeMismatch = typeof config !== typeof defaultValue + + if (isTypeMismatch) { + newConfig = defaultValue + } else { + // Check if there are missing properties + let hasMissingProperty = false + for (const key in defaultValue) { + if (!(key in config)) { + hasMissingProperty = true + break + } } + + newConfig = hasMissingProperty ? { ...defaultValue, ...config } : config } - // Merge iff there are missing properties - return hasMissingProperty ? { ...defaultValue, ...config } : config + + if (newConfig !== config) { + const jsonString = JSON.stringify(newConfig) + localStorage.setItem(key, jsonString) + } + + return newConfig }, storageAtom.write) }