Last active
June 11, 2020 10:37
-
-
Save lski/29b42f79a6d976bfedf8f03550948475 to your computer and use it in GitHub Desktop.
Creates a persistent store for data, meaning the key is encapsulated and the data is parsed to/from a string for you.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
export const createStorage = (key, scope = localStorage) => { | |
return { | |
get() { | |
const stored = scope.getItem(key); | |
if (stored === null) { | |
return null; | |
} | |
return JSON.parse(stored); | |
}, | |
set(item) { | |
scope.setItem(key, JSON.stringify(item)); | |
return item; | |
}, | |
remove() { | |
scope.removeItem(key); | |
}, | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const createStorage = <T>(key: string, scope = localStorage) => { | |
return { | |
get(): T | null { | |
const stored = scope.getItem(key); | |
if (stored === null) { | |
return null; | |
} | |
return JSON.parse(stored); | |
}, | |
set(item: T): T { | |
scope.setItem(key, JSON.stringify(item)); | |
return item; | |
}, | |
remove(): void { | |
scope.removeItem(key); | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment