James111
James111

Reputation: 15903

React-native render method running twice on load

I've searched everywhere for a proper solution to this but I can't find one! When I open up my emulator & when my app has loaded it runs the render method twice. This means I only get the InitialState from my redux-store.

Here are my start scripts:

"scripts": {
    "android-setup-port": "adb reverse tcp:8081 tcp:8080",
    "start": "env NODE_ENV=DEV rnws start --hostname localhost",
    "build": "env NODE_ENV=PRODUCTION rnws bundle",
    "test": "eslint src",
    "debugger-replace": "remotedev-debugger-replace --hostname localhost --port 5678",
    "remotedev": "npm run debugger-replace && remotedev --hostname localhost --port 5678"
  },

Here is my layout:

  componentWillMount() {
    this.props.actions.fetchalbum("1");
  }

  render() {
    var album = this.props.album;

    console.log("\n\nlayout_____", album); // THIS IS PRINTED OUT TWICE

    // Create the feed
    var albumObj = [];

    for (var i = 0; i < album.albums.length; i++) {
      feedObj.push(
        <View key={i}>
          <AlbumComp post={ album.albums[i] }/>
        </View>
      );
    }

    return (  
      <ScrollView>
        { albumObj }
      </ScrollView>
    )
  }
};

When I open the app it console.logs the album with it's intial state & then again with it's new state which is retrieved from an API using the fetch method.

Any ideas to how I can fix this?

Upvotes: 1

Views: 3313

Answers (1)

jevakallio
jevakallio

Reputation: 35890

The application behaves exactly as it should - it renders once when the component is mounted, and then again after the asynchronous call updates the state again.

You cannot prevent the initial rendering of the application root component. However what you can do is to handle the un-loaded state in your render method by e.g. showing a loading spinner before the data is loaded. Perhaps something like:

render() {
  var album = this.props.album;
  if (!album) {
    return <ActivityIndicatorIOS />;
  }

  console.log("\n\nlayout_____", album);

  //...
}

Upvotes: 3

Related Questions