Shivam Pokhriyal
Shivam Pokhriyal

Reputation: 1094

How to reload flat list in React-Native?

I am switching from android to react native. Complete naive. I wanted to implement something like recyclerview in react native and found out about FLATLIST Now the problem is initially my data variable is empty and later on i am adding data into that variable. Now how do i notify the flat list that the data has changed and it should now re render itself.

Like in recyclerview we use adapter.notifyDataSetChanged(); to inform the recycler view about the change that it should re-render itself now

The code i am using is

export default class Convo extends Component{

constructor(props){
super(props);
this.state = {
  loggedIn: 'false',
  title: 'Login/SignUp',
  messages: []
};
this.downloadConversation = this.downloadConversation.bind(this);
}

componentDidMount(){
this.downloadConversation();
}

 downloadConversation(){
    this.setState(
      {message: [
        {
            key: "HIHI",
            name: "lets  this bullshit",
            message: "I i i"
          },
          {
              key: "HIHI2",
              name: "lets change  bullshit",
              message: "I i i"
            },
            {
                key: "HIHI3",
                name: "lets change this ",
                message: "I i i"
              }
      ]}
    );
//After updating the messages object, i want to notify flat list about 
//the change, basically i will be updating this object asynchronously  
// in background which will take time. for now i am updating directly 
//to show you
}


renderFlatListItem(item) {
return (
  <View key={item.key} style={styles1.flatviewItem}>
     <Text>User1</Text>
     <Text style={styles1.name}>{item.name}</Text>
     <Text style={styles1.messageStyle}>{item.message}</Text>
   </View>
   )
   }

 render(){
  return(
    <View style={styles1.container}>
      <View style={styles1.header}>
        <Text style={styles1.h2style}>Conversation List</Text>
      </View>
      <FlatList
        style={styles1.flatview}
        extraData={this.state}
        keyExtractor={item=>item.key}
        showsVerticalScrollIndicator={true}
        data={this.state.messages}
        renderItem={({item}) => this.renderFlatListItem(item)}
      />
    </View>
  );
 }

}

Upvotes: 1

Views: 6554

Answers (1)

Nunchucks
Nunchucks

Reputation: 1230

Your component should automatically re-render when the component state changes (if anything in your render method references the changed piece of state). I think you just need to change 'message' to 'messages' when you setState in your downloadConversation() method. Your FlatList is looking for this.state.messages, not this.state.message and this.state.messages is never changed. Just fix that typo & hopefully that fixes it.

Upvotes: 1

Related Questions