LPFJ
LPFJ

Reputation: 195

How To Refresh Data Every Time Opening The Page In React Native?

Current Code

App.js

const Mypage = {
  screen: MypageScreen,
  navigationOptions: () => ({
    headerShown: false,
  }),
};

const MypageStack = createStackNavigator(
  { Mypage },
  {
    initialRouteName: 'Mypage',
    navigationOptions: {
      title: 'Mypage',
    },
  },
);

const postLoginNavigator = createBottomTabNavigator({
  Mypage: MypageStack,
});

const AppNavigator = createStackNavigator({
  Loading,
  ...,
  PostLogin: postLoginNavigator,
}, {
  mode: 'modal',
  headerMode: 'none',
  initialRouteName: 'Loading',
});

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  render() {
    return (
      <AppContainer />
    );
  }
}

Mypage.js

export default class Mypage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: '',
    };
  }

  async componentDidMount() {
    // getting how many items this user have
    const items = await db.getAllItems()
    // items is an array
    this.setState({
      items: items.length,
     });
  }

  render() {
    return (
      <View>
        <Text>Items</Text>
      </View>
      <View>
        <Text>
          { this.state.items }
        </Text>
      </View>
    );
  }
}

What I'm Trying To Do

I want the datas to be refreshed When every time I open mypage tab.

The number of items in mypage.js is changing, so I want updated number of items.

Or when only number of items changes, I want updated number.

I would appreciate it if you could give me any advices.

Upvotes: 1

Views: 2196

Answers (2)

Waheed Akhtar
Waheed Akhtar

Reputation: 3187

As looking into your code you are using react-navigation v4 maybe, So you have to add Event Listener for every focus on the tab it will be called and will fetch new data.

componentDidMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener('didFocus', () => {
  // The screen is focused
  // Call any action
});

}

For more information about events have a look at this.

https://reactnavigation.org/docs/4.x/function-after-focusing-screen/#triggering-an-action-with-a-didfocus-event-listener

Upvotes: 1

Imjaad
Imjaad

Reputation: 604

For just checking number of items, you can always use items.length, but if you are looking for the case when your state should actually get updated data you can use shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState){
  return nextState.items != this.state.items;
}

Upvotes: 0

Related Questions