From a941b8650bfc6bdc70ae15923385f31a19bee5d9 Mon Sep 17 00:00:00 2001 From: Alecs Farias Date: Mon, 10 Apr 2023 17:54:31 -0300 Subject: [PATCH] fix: add Map and Set checks for parse and stringify --- src/useLocalStorage/useLocalStorage.ts | 33 ++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/useLocalStorage/useLocalStorage.ts b/src/useLocalStorage/useLocalStorage.ts index a6b66602..eee80a2a 100644 --- a/src/useLocalStorage/useLocalStorage.ts +++ b/src/useLocalStorage/useLocalStorage.ts @@ -27,7 +27,24 @@ function useLocalStorage(key: string, initialValue: T): [T, SetValue] { try { const item = window.localStorage.getItem(key) - return item ? (parseJSON(item) as T) : initialValue + + if(!item) { + return initialValue + } + + const parsed = parseJSON(item) as T + + //considering that the initial value is a Map, convert object to map + if(initialValue instanceof Map) { + return new Map(Object.entries(parsed as Object)) as T + } + + //considering that the initial value is a Set, convert the array to set + if(initialValue instanceof Set) { + return new Set(parsed as Array) as T + } + + return parsed } catch (error) { console.warn(`Error reading localStorage key “${key}”:`, error) return initialValue @@ -53,7 +70,7 @@ function useLocalStorage(key: string, initialValue: T): [T, SetValue] { const newValue = value instanceof Function ? value(storedValue) : value // Save to local storage - window.localStorage.setItem(key, JSON.stringify(newValue)) + window.localStorage.setItem(key, stringify(newValue)) // Save state setStoredValue(newValue) @@ -101,3 +118,15 @@ function parseJSON(value: string | null): T | undefined { return undefined } } + +function stringify(value: T): string { + if(value instanceof Map) { + return JSON.stringify(Object.fromEntries(value)) + } + + if(value instanceof Set) { + return JSON.stringify(Array.from(value)) + } + + return JSON.stringify(value) +}