Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Map & Set to useLocalStorage control #309

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/useLocalStorage/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,24 @@ function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T>] {

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<any>) as T
}
Comment on lines +35 to +45
Copy link
Author

@AlecsFarias AlecsFarias Apr 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gonna write this here because I think it is more like to be a question on this pr than a part of it's description.

'Why not put this Map and Set creation logic inside parseJSON function ? "

I did this way because I think that it was no good to add a new parameter to parseJSON function just to say that it would be a Map or Set. Considering that is no more than this 2 instance checks I think that it would have no problem to stay this way, but, open for tips and discussions !


return parsed
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error)
return initialValue
Expand All @@ -53,7 +70,7 @@ function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T>] {
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)
Expand Down Expand Up @@ -101,3 +118,15 @@ function parseJSON<T>(value: string | null): T | undefined {
return undefined
}
}

function stringify<T>(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)
}