Search code examples
javascriptreactjsreact-nativereact-navigationreact-native-flatlist

Flatlist data is lost when changing screens


I have a screen that displays a Flatlist with some data in it, but when I go back to the previous screen and come back back to this acreen with the Flatlist, the data is not more there. I use React Navigation to move between screens and also to move data.

This is the code I use to go back:

onPress={() => this.props.navigation.goBack()}

Solution

  • When you are on the first page, only that page is mounted. Then you go to page2 with the Flatlist. Now both page1 and page2 are mounted.

    When you use navigation.goBack(), page2 is unmounted. This means this.state on page2 is deleted.

    So now when you go to page2 for the second time, it is re-mounted (so a new/empty state is used)

    If you want to preserve the state between mount/unmount/re-mount, you will either need a state management tool, or pass all data via the navigator.