React Native: Force reload of TabBarIOS.item

1.9k Views Asked by At

I have a TabBar based app in React Native. Multiple tabs use the same datasource (AsyncStorage). If I'm now updating the data in one tab and open the other one, the old data is displayed. I can't figure out, how to force a reload every time the item become active.

  1. FavoritesView: display saved data
  2. ExploreView: Manipulate saved data
  3. FavoritesView: expired data gets displayed (--> force reload)

    <TabBarIOS.Item
    title="Explore"
    icon={{uri:'ic_explore'}}
      selected={this.state.selectedTab === 'exploreTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'exploreTab'
        });
      }}>
      <ExploreView/>
    </TabBarIOS.Item>
    
    <TabBarIOS.Item
      title="Favorites"
      icon={{uri:'ic_favorite_border'}}
      selected={this.state.selectedTab === 'favoriteTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'favoriteTab'
        });
      }}>
       // Reload this
      <FavoritesView/>
    </TabBarIOS.Item>
    
    <TabBarIOS.Item
      systemIcon="more"
      selected={this.state.selectedTab === 'moreTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'moreTab'
        });
      }}>
      <MoreView/>
    </TabBarIOS.Item>
    

I already tried to set a new state to trigger an update, but it doesn't seem to change anything.

<TabBarIOS.Item
      title="Favorites"
      icon={{uri:'ic_favorite_border'}}
      selected={this.state.selectedTab === 'favoriteTab'}
      onPress={() => {
        this.setState({
          selectedTab: 'favoriteTab',
          forceUpdate: Math.random()
        });
      }}>
      <FavoritesView forceUpdate={this.state.forceUpdate}/>
</TabBarIOS.Item>
2

There are 2 best solutions below

1
On

this references the parent component when using fat arrow notation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this).

Try adding a ref to the TabBar item and use this.refs.refName.forceUpdate() (slightly nicer than updating the state with a random value as well).

1
On

I had a similar issue and what eventually worked for me was to override componentWillReceiveProps on the embedded views. It gets called anytime the view is set as selectedTab in the TabBarIOS.

https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops