gaidediz
gaidediz

Reputation: 59

AsyncStorage.getItem with state values

I new to react native, I trying to set AsyncStorage.getItem and AsyncStorage.setItem to save my state values,I setup the AsyncStorage.setItem in componentWillMount() function, in the first time my app is running I have state that my component use and he have some keys with specific values, if I setup the AsyncStorage.setItem to get the last item from my state, my component fails.

  constructor(props) {
    super(props);
    this.state = { userAnswer: '', count: 0};
  }

 componentWillMount(){
  AsyncStorage.getItem("userAnswer").then((value) => {
    this.setState({userAnswer: value})}).done();
  AsyncStorage.getItem("count").then((value) => {
    this.setState({count: value})}).done();
  }

saveData(){
  AsyncStorage.setItem("userAnswer",this.state.userAnswer);
  AsyncStorage.setItem("count",this.state.count);
};

I need that in the fist time the app is running the state should be the same meaning the count should stay 0, in my error the count appear as null

every help really appreciated! thanks.

Upvotes: 1

Views: 1043

Answers (1)

Alexander Vitanov
Alexander Vitanov

Reputation: 4141

Change it to this:

AsyncStorage.getItem("count").then((value) => {
    this.setState({count: value || 0})}).done();
  }

Upvotes: 2

Related Questions