Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating this.state.dataSource doesn't update ListView

Tags:

react-native

I have a ListView like:

<ListView
      dataSource={this.state.dataSource}
      renderRow={this.renderMovie}
      style={styles.listView}
/>

It displays rows like:

  <View style={styles.container}>
      <TouchableHighlight onPress={this._onPressButton.bind(this,movie)}>

        <Image
          source={{uri: movie.uri}}
          style={styles.thumbnail}
        />
    </TouchableHighlight>
    <View style={styles.rightContainer}>
      <Text style={styles.title}>{movie.id}</Text>
      <Text style={styles.year}>{movie.votes}</Text>
    </View>
  </View>

I have a function that updates this.state.dataSource with the number of "votes" a movie has. But these changes aren't reflected in the UI, but when I log the this.state.dataSource, the changes are there. Do I need to somehow re-render the rows? Shouldn't they automatically change?

Thanks!

like image 306
Zach Lucas Avatar asked Apr 29 '15 02:04

Zach Lucas


2 Answers

I have a similar situation and the only thing I had to do is:

this.setState({
  dataSource: this.ds.cloneWithRows(new_data_for_datasource)
})

It works fine for me. In the class constructor I have the following code:

this.ds = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2
})
this.state = {
  dataSource: this.ds.cloneWithRows(this.props.original_data)
}

Hope it helps!

like image 137
Niccolò Passolunghi Avatar answered Jan 27 '23 18:01

Niccolò Passolunghi


To make React-native re-render the rows, you need to create a copy of the array, update your object, and then use setState with your newly created array. For example:

let newArray = this.state.dataSource.slice();
newArray[indexToUpdate] = {
  ...this.state.dataSource[indexToUpdate],
  field: newValue,
};
this.setState({
  dataSource: this.state.dataSource.cloneWithRows(newArray),
});

Reference:

  • React-Native Updating List View DataSource
  • ListView does not re-render a row when property of an object in datasource array is changed #4104
like image 22
heitortsergent Avatar answered Jan 27 '23 19:01

heitortsergent