React Native: When / How to Run Network Requests?

While playing with React Native, I came across a problem, and I'm not sure how to solve it. I have a main NavigatorIOSview where the content is pushand popis located around different views. I initially configured it so that the network request will be launched in componentDidMount. However, it began that the β€œpressing” of navigation (animation of the transition to the next screen) will be delayed until the actual request is completed (although it uses fetch, promises and, when loading async/await). I managed to compensate for most of these problems by wrapping the network request code in the call setTimeout(fn, 0), but I'm not sure if this is the right way to handle this. Both requestAnimationFrameand InteractionManager.runAfterInteractionsare not working, and even setTimeoutis completed. Are there any better ways to do this?

Just to illustrate, this is roughly how my code (pseudocode) works:

Screen 1 :

<TouchableHighlight onPress={() => this.navigator.push({ data })} />

Screen 2 :

componentDidMount() {
  this.startLoading();
}

startLoading() {
  this.setState({ items: [], loading: true });
  this.load().then(items => this.setState({ items, loading: false }));
}

async load() {
  const contents = await fetch(this.props.url);
  // Process contents.
  return items;
}
+4
source share
2 answers

Have you tried setting the default data in getInitialState?

var TouchableHighlight = React.createClass({
  getInitialState: function() {
    return {
      items: [],
      loading: true
    };
  }

https://facebook.imtqy.com/react/tips/initial-ajax.html

0
source

The function setStatedoes not immediately trigger a rendering event, so it startLoadingdoes not need the first line. Setting up the initial state, such as Winnie's answer, is the best solution for this.

I see that you are using es7, but can you try this?

componentDidMount() {
    fetch(this.props.url)
        .then(result => this.setState({items: processContents(result), loading: false}))
        .catch(e => console.log("error", e))
}

processContents(fetchResult) {
    // do whatever
    return {};
}
0
source

All Articles