Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refresh React state after running navigator.pop()?

While working with React Native, I have a few components that are pushed on top of each other, some of which change the state of the component below them, like so:

Social -> Groups -> Add Group

However, when I run navigator.pop() to get back to the previous component (for example, after adding a group to a user's account), the component underneath (in this case, 'Groups') won't refresh with the latest state.

What am I doing wrong here?

like image 374
Smee Avatar asked Mar 04 '16 04:03

Smee


1 Answers

Turns out I was able to solve this by inserting a componentWillUpdate on the 'Groups' component, that is, whenever the Groups component updates, it triggers a loadGroupsData function:

componentWillUpdate() {
  this.loadGroupsData();
}

...to which the loadGroupsData function checks for any differences, and if any are present, it loads:

loadGroupsData() {
api.getUserGroups(this.state.userId, (data) => {
  data.forEach((group, index) => {
    group.groupname = group.groupname;
  });
  if (this.state.dataSource._cachedRowCount === undefined || this.state.dataSource._cachedRowCount !== data.length) {
    this.setState({
      usersGroups: data.map(data => data.groupname),
      dataSource: this.state.dataSource.cloneWithRows(data),
      loaded: true,
    });
  }
});} 
like image 176
Smee Avatar answered Nov 13 '22 02:11

Smee