Search code examples
react-nativereact-native-flatlistuse-effectpage-refreshpull-to-refresh

How do I refresh the page with an onPress in ReactNative


I am new to ReactNative and have encountered an issue regarding page refreshing. I have some filters in my screen and will like the page to refresh once any of these filters are pressed, but am unable to find any guides on how to do so. I have searched endlessly but only found numerous guides on refreshing with pulldown, and I feel like the solution has something to do with React.useEffect but am unfamiliar with that.

The important parts of my code are as below:

The TouchableOpacity component to trigger the refresh:

                        <TouchableOpacity
                            style={styles.filterButton}
                            onPress={() => {
                                sortByRating()
                            }}
                        >

where sortByRating() is a function to sort my eateriesToShow array based on their ratings.

The FlatList I want to be refreshed on filter:

                <FlatList
                    data={eateriesToShow}
                    keyExtractor={item => item.id.toString()}
                    renderItem={renderItem}
                    showsVerticalScrollIndicator={true}
                />
            </View>
        )
    }

Currently my eateriesToShow array gets sorted, but the FlatList does not get refreshed. Any help will be appreciated.


Solution

  • You want your flatist to update when the data is changed. refreshing your flautist is another thing. So what I suggest you to do is use the useState hook.

     const [yourList, setYourList] = useState<string | null>(null)
    

    like this (you don't need the types if you are using javascript instead of typescript)

    and then when sorting by rating you should do setYourList(newEateriesArray)

    and your flautist should update.