Created
December 3, 2019 13:05
-
-
Save ngoclt/c1bf212c7b1e3aa928b091b8fb7bad8c to your computer and use it in GitHub Desktop.
Generic functions for loading and saving values with AsyncStorage in 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
import {AsyncStorage} from 'react-native'; | |
export function setValue(key: string, value: any): Promise<void> { | |
return AsyncStorage.setItem(key, JSON.stringify(value)); | |
} | |
export function getValue<T>(key: string, defaultValue: T = null): Promise<T> { | |
return new Promise((resolve, reject) => { | |
AsyncStorage.getItem(key).then((value) => { | |
if (value !== null) { | |
resolve(JSON.parse(value)); | |
} else { | |
resolve(defaultValue); | |
} | |
}).catch( (error) => { | |
reject(error); | |
}); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment