admin管理员组

文章数量:1323336

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.

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.

Share Improve this question asked Oct 6, 2017 at 17:15 Scott SanzenbacherScott Sanzenbacher 952 silver badges4 bronze badges 3
  • The callback for setItem will only give you an error, if an error occurred. It does not give you the value that you set. facebook.github.io/react-native/docs/asyncstorage.html#setitem – Sidney Commented Oct 6, 2017 at 17:19
  • According to the documentation, setItem() can be called with a third parameter, an optional error callback. Your val is most likely undefined. – user5734311 Commented Oct 6, 2017 at 17:20
  • Thank you. I'll try out my other code and re-ask this one. – Scott Sanzenbacher Commented Oct 6, 2017 at 17:22
Add a ment  | 

2 Answers 2

Reset to default 6

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'}))

本文标签: javascriptAsyncStoragesetItem Callback Always NullStack Overflow