fahi
fahi

Reputation: 55

AsyncStorage it's asynchronous and i can't doing what i want

I'm new in react native and i have faced issue takes from me more than 3 days ^_^

I'm using " AsyncStorage " in componentDidMount but it's using the init value because the asynchronous still not returning the value

var data = {foo:this.state.parmstudentid};
fetch(`http://****:82/wasily/MyDealOffer.php?UserID=${data.foo}`, 

when is put the url "http://****:82/wasily/MyDealOffer.php?UserID=4" it's returning the correct list , but when i use ${data.foo} it's not returning the list because it's sending "0" to the api ( the default value when creating the state )

AsyncStorage.getItem("UserID").then((value) => {
this.setState({parmstudentid: value});
}).done(()=>{
this.setState({AsyncResult:true})
})

i have used this code to bring the new value for my parmstudentid state

how i can stop running the all code until the AsyncStorage run

Upvotes: 0

Views: 331

Answers (1)

Doug Friedman
Doug Friedman

Reputation: 46

You probably want something like this right?

AsyncStorage
  .getItem("UserId")
  .then( val => {
    this.setState({ parmstudentid: val });
    fetch(`http://****:82/wasily/MyDealOffer.php?UserID=${val}`)
    // etc
  })

The setState portion may not even be necessary if you just use the value that one time. Or if you need a more complex set of of loading actions, you can follow this type of pattern:

export default class App extends Component {
  componentWillMount(){
    AsyncStorage
      .getItem("UserId")
      .then( val => this.setState({ parmstudentid: val, loading: false }) );
  }

  componentWillUpdate(props, state){
    if(!state.loading){
      // make your callout here
    }
  }

  render() {
    return (
      <View />
    );
  }
}

Upvotes: 1

Related Questions