Last active
July 26, 2020 18:10
-
-
Save justsml/e3a186b8dfe4f62f7cb2d0675a26c732 to your computer and use it in GitHub Desktop.
Add auto JSON encoding to `localStorage` & `AsyncStorage` (from React Native)
This file contains hidden or 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
/** | |
Utility for React Native's AsyncStorage module. | |
Auto encodes/decodes using `JSON`. | |
Essentially data is saved as key/value to available flash/SD storage. | |
*/ | |
import { AsyncStorage } from "react-native" | |
export default { | |
setItem(key, value) { | |
return AsyncStorage.setItem(key, JSON.stringify(value)) | |
}, | |
getItem(key) { | |
return AsyncStorage.getItem(key) | |
.then(data => data ? JSON.parse(data) : undefined) | |
}, | |
removeItem(key) { | |
return AsyncStorage.removeItem(key) | |
} | |
} |
This file contains hidden or 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
/** | |
Utility for localStorage browser API w/ auto encoded/decoded data using `JSON`. | |
*/ | |
const jsonStore = { | |
setItem(key, value) { | |
value = JSON.stringify(value) | |
return localStorage.setItem(key, value) || value | |
}, | |
getItem(key) { | |
let value = localStorage.getItem(key) | |
return value ? JSON.parse(value) : undefined | |
}, | |
removeItem(key) { | |
let value = localStorage.getItem(key) | |
if (key) localStorage.removeItem(key) | |
return value | |
}, | |
reset() { | |
localStorage.clear() | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment