0

I'm working with AsyncStorage, I need to get the value stored into "facoltà" and save it into "promessa" calling this.setState. I wrote that code:

constructor(props){
  super(props)
  AsyncStorage.setItem("facoltà","PROFS.json")
}
componentWillMount(){
  AsyncStorage.getItem("facoltà").then((value)=>
  { 
    console.log(value); // the console returns me PROFS.json so I thought it was working
    this.setState({promessa:value})
  }):
  var dataObjects=require("../JsonLists/"+this.state.promessa) // but here this.state.promessa returns me null
 }

the problem is that this.state.promessa returns me "null" instead of "PROFS.json" and I can't figure out how to solve it. Thanks in advance for your answers.

Matteo Veraldi
  • 45
  • 2
  • 10
  • You won't be able to import your file with this way : `require("../JsonLists/"+this.state.promessa)`. You can not dynamically import files. Take a look at [this answer](https://stackoverflow.com/a/43517912/5555458) to understand why. – Antoine Grandchamp Jul 21 '17 at 18:24
  • Thank you, I fixed the require error that I made as Antoine Grandchamp said. Then I fixed the dataObject issue placing it into the then chain as you said, thank you. – Matteo Veraldi Jul 23 '17 at 19:59

5 Answers5

2

ComponentWillMount will not finish the getItem Promise after the setItem Promise in the constructor.

try :

componentWillMount(){
 AsyncStorage.setItem("facoltà",PROFS.json)
}

render(){
...
  AsyncStorage.getItem("facoltà").then((value)=>alert(value));
...
}

this should alert your data.

Mustafa Tawfig
  • 353
  • 1
  • 3
  • 9
0

AsyncStorage.getItem returns a promise, thus will be resolved in the callback with then. That means your next line var dataObjects=require("../JsonLists/"+this.state.promessa) is executed before the promise is resolved.

You should put the line within the then callback and have a default initial value if you need dataObjects immediately in your componentWillMount method.

hyb175
  • 1,291
  • 8
  • 13
0

I think it's a timing issue. You're using a promise with .then, which is setting the state after var dataObjects is trying to require it.

Have you tried placing the var dataObjects inside your .then code?

stevenlacerda
  • 1,187
  • 2
  • 9
  • 21
0
async myMethode() {
AsyncStorage.getItem("").then((value)=>alert(value));

}

try like this.Call methode where it required

0

Using Async/Await.

async componentDidMount () {


    try {

        const item = await this.someMethodAsync();

    } catch (e) {

       console.log("Error getting item", e);
    }
}    

async someMethodAsync () {
     try {

          let item = AsyncStorage.getItem("foo");
          console.log(item);
     catch (e) {
          throw e;
     }

     return item; // Could be any value, including null.
}
Lee Brindley
  • 6,242
  • 5
  • 41
  • 62