Reputation: 430
I followed the documentation sample about AsyncStorage:
React Native - AsyncStorage docs
. so, I implemented my code:
var STORAGE_KEY = '@AsyncStorageExample:key';
and i define my class with this functions:
I have a initial state:
state={
defineValor: 0,
};
and the componentDidMount
function and _loadInitialState
:
componentDidMount() {
this._loadInitialState().done();
};
_loadInitialState = async () => {
try {
var value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null){
this.setState({defineValor: value});
alert('Recovered selection from disk: ' + value);
} else {
alert('Initialized with no selection on disk.');
}
} catch (error) {
alert('AsyncStorage error: ' + error.message);
}
};
So i made a function to change the state with AsyncStorage, as well as in the documentation:
changeState = () => {
this.setState ({
defineValor: 1
});
try {
AsyncStorage.setItem(STORAGE_KEY, this.state.defineValor);
alert('Saved selection to disk: ' + this.state.defineValor);
} catch (error) {
alert('AsyncStorage error: ' + error.message);
}
};
So, when i open the app, all the process run, alert "Initialized with no selection on disk" and when i call my function changeState
, he's alert "Saved selection to disk: 1". But when i close de app and reopen, the state was not saved, and he's alert "Initialized with no selection on disk.". What am I doing wrong?
Upvotes: 0
Views: 3015
Reputation: 1889
setState
has a callback do the AsyncStorage.setItem
in that callback.
Also AsyncStorage accepts only string as value
this.setState({ defineValor: string }, () => {
try {
AsyncStorage.setItem(STORAGE_KEY, this.state.defineValor);
alert('Saved selection to disk: ' + this.state.defineValor);
} catch (error) {
alert('AsyncStorage error: ' + error.message);
}
});
Upvotes: 2