Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active July 26, 2020 18:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justsml/e3a186b8dfe4f62f7cb2d0675a26c732 to your computer and use it in GitHub Desktop.
Save justsml/e3a186b8dfe4f62f7cb2d0675a26c732 to your computer and use it in GitHub Desktop.
Add auto JSON encoding to `localStorage` & `AsyncStorage` (from React Native)
/**
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)
}
}
/**
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