AsyncStorage.setItem Callback Always Null

Viewed 5253

I'm trying to use AsyncStorage to set a value and it always seems to be setting null. I've used async/await in order to do this but I've also tried to whittle down the troubleshooting to just setting a value and checking the callback and I'm still getting null. Any ideas what I'm doing wrong here?

AsyncStorage.setItem('something', 'VALUE') 
  .then((val) => { 
    this.setState({storageValue: val ? val : 'EMPTY'});
  })

This always gives me "EMPTY" in my state.

2 Answers

I can't find it in the documentation but according to the sample code code setItem does not seem to return anything (the result is ignored in sample code) so maybe the promise does not resolve to anything either.

You could try setting it and then getting it:

AsyncStorage.setItem('something', 'VALUE')
.then(x => AsyncStorage.getItem('something')
.then((val) => { 
  this.setState({storageValue: val ? val : 'EMPTY'});
})

Is there a reason why you can't just use whatever you're passing into the setItem? You can use that same variable:

AsyncStorage.setItem('something', val) 
  .then(() => this.setState({storageValue: val ? val : 'EMPTY'}))
Related