Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - How to refresh FlatList when back to previous page?

Tags:

I will try to explain my case:

I have 2 pages/screens

SreenA.js :

...
<FlatList>
</FlatList>
...

ScreenB.js :

...
<Button> This button for back to ScreenA </Button>
...

What i want to achieve :

When i press back button in screenB , my app will back to screenA. When i come back to screenA , i need to refresh the FlatList. (each time i back to screenA).

How i achieve that case in Android Native ?

I add this section to help you to more understand what challenge i face. In Android Native, i will use onResume to refresh the list (onResume called everytime the screen/page called).

What i already try but not work for me now :

I already try this but what i get it just called when app in background and then show in foreground :

state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
      //i place the code here for refresh the flatList. But not work
    }
    this.setState({appState: nextAppState});
  }
like image 709
Crocodile Avatar asked Oct 27 '18 16:10

Crocodile


1 Answers

Add navigation.addListener to fire every time a page receives navigation focus.

As an example:

class Page1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ts: 0 }

    // this will fire every time Page 1 receives navigation focus
    this.props.navigation.addListener('willFocus', () => {
      this.setState({ ts: Date.now() })
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Page 1 [{this.state.ts}]
        </Text>
        <Button title="Page 2" onPress={() => this.props.navigation.navigate('Page2')}/>
      </View>
    );
  }
}

For the full example, check the following snack on your phone. The timestamp will update every time you navigate back to page 1 but not when the app resumes.

You should be able to expand it for your needs from this example.

like image 50
Wainage Avatar answered Nov 15 '22 04:11

Wainage