I create a file GetSetStorage
include AsyncStorage
, when i try to use it i find its no working.
Here is my GetSetStorage
file:
import { AsyncStorage } from 'react-native';
class GetSetStorage {
setStorageAsync(key, value) {
console.log('start set storage');
console.log(`key =>${key}`);
console.log(`vaue =>${value}`);
return new Promise((resolve, reject) => {
console.log('Why is no working here ?');
AsyncStorage.setItem(key, value, (error) => {
console.log(error);
if (error) {
console.log('===');
console.log(`set${key}error${error}`);
console.log('===');
reject(`set${key}error${error}`);
} else {
console.log('===');
console.log(`set${key}succeed`);
console.log('===');
resolve(true);
}
});
});
}
getStorageAsync(key) {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(key, (error, result) => {
console.log(error);
console.log('where is my error');
if (error) {
console.log('===');
console.log(`load ${key} error ${error}`);
console.log('===');
reject(`load ${key} erro ${error}`);
} else {
console.log('===');
console.log(`load ${key} succeed`);
console.log('===');
resolve(result);
}
});
});
}
}
export default new GetSetStorage();
I use it in my component like this:
import GetSetStorage from '../storage/GetSetStorage';
componentWillMount() {
GetSetStorage.setStorageAsync('testKey', 'test value');
}
I see my console.log i find setItem
is no working. Why ?
Any help would be appreciated. Thanks in advance.
//check it out !
state = {
UserEmail: '[email protected]'
}
async setValue() {
await AsyncStorage.setItem('email', JSON.stringify(this.state.UserEmail));
}
async getValue() {
try {
const value = await AsyncStorage.getItem('email');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}