user938363
user938363

Reputation: 10350

How to fetch async data after componentWillMount deprecated?

componentWillMount will be removed from the future release of React Native. My app needs to fetch async API data from the server before rendering, then how to do it? The constructor can't be async. Or I have to use promise().then in constructor?

Upvotes: 1

Views: 400

Answers (3)

hong developer
hong developer

Reputation: 13916

I think we should use loading because it means we have to work on the data before the screen is visible.

example.js

...
this.state={
     loading: false
}
....

async ComponentDidMount() {
     ....
     await your code
     ....
    this.setState({
      loading: true
    });
}

...

render{
   if(this.state.loading === false){
     <View style={[styles.container, styles.horizontal]}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
   return(...);
  }
...


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center'
  },
  horizontal: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 10
  }
})

Upvotes: 1

Francesco Meli
Francesco Meli

Reputation: 2700

I would use componentDidMount.

Because of the nature of async events in JavaScript, when you kick off an API call, the browser goes back to doing other work in the meantime. When React is rendering a component, it doesn’t wait for componentWillMount to finish whatever it started.

So componentWillMount over componentDidMount wasn't probably giving you any advantages anyways.

Upvotes: 2

Jonas Rosenqvist
Jonas Rosenqvist

Reputation: 372

I think you're supposed to use ComponentDidMount instead. The fact that the component is rendered without data is best handled by using a loading flag in your state.

Upvotes: 1

Related Questions