ListView.DataSource looping data for React Native

- 1 answer

Ad

When I do a Console.log(this.state.dataSource) I get the image as below, I'm currently getting "Row goes here!"x 4 because the API return 4 results.

I tried to retrieve the user data like email but it wont "loop" and print accordingly.

I'm not exactly sure how this code works, comments would help abit.Please Advice

enter image description here

    var messagesTab = React.createClass({
  componentWillMount: function() {
    fetch('https://randomuser.me/api/?results=4')
      .then(res => res.json())
      .then(res => this.updateDataSource(res));
  },
  getInitialState: function() {
    return {
      dataSource: new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      })
    };
  },
  updateDataSource: function(data){
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(data)
    })
  },
  renderRow: function (){
    return (
      <View>
        <Text>Row goes here!</Text>
      </View>
    );
  },
  render: function(){
    console.log(this.state.dataSource);
    return (
      <View style={ styleseact.container }>
        <ListView dataSource={ this.state.dataSource } renderRow={ this.renderRow } />
      </View>
    );
  }
});

enter image description here

I got this when I did a console.log(data); on renderRow

Ad

Answer

Ad

You're overwriting your DataSource declaration. Split up the declaration and update.

Declare this before React.createClass:

var ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2
});

Remove it from getInitialState:

getInitialState: function() {
  return {
    dataSource: ds.cloneWithRows([])
  };
},

And reference it in the update function:

updateDataSource: function(data){
  this.setState({
    dataSource: ds.cloneWithRows(data)
  })
},
Ad
source: stackoverflow.com
Ad