Skip to content

Instantly share code, notes, and snippets.

@ngoclt
Created December 3, 2019 13:05
Show Gist options
  • Save ngoclt/c1bf212c7b1e3aa928b091b8fb7bad8c to your computer and use it in GitHub Desktop.
Save ngoclt/c1bf212c7b1e3aa928b091b8fb7bad8c to your computer and use it in GitHub Desktop.
Generic functions for loading and saving values with AsyncStorage in React Native.
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