I'm creating a live chat app using React Native.
I'm using <FlatList>
for the chat channel list on the main screen, and I'm using StackNavigator for the navigation between screens.
Now I am trying to let the <FlatList>
refetch data from the back-end and rerender itself whenever user navigate back to the main screen.
An example will be a user enters a chat channel, the app navigates to the chat detail screen, the user sends some messages there, when the user press the back button and navigates back to the main chat channel list screen, the <FlatList>
should refectch from the back-end and rerender itself to show the latest data. (reorder the most recent channel to the top etc.)
Right now pull to refresh is implemented but the problem is how do I know that the user has navigated back to the main screen and how to actively call refresh on <FlatList>
when that happens.
Here is some of my code:
onRefresh = async () => {
const { data } = this.props
try {
this.setState({ refreshing: true })
await data.refetch({ page: 1 })
} catch (e) {
// todo
} finally {
this.setState({
refreshing: false,
})
}
}
const NudgeList = ({
nudges,
loading,
refreshing,
onRefresh,
}) => {
let inner
if (loading && !refreshing && !fetchingMore) {
inner = (
<View style={styles.center}>
<ActivityIndicator animating />
</View>
)
} else {
inner = (
<FlatList
onRefresh={onRefresh}
refreshing={refreshing || false}
scrollEventThrottle={400}
data={nudges}
renderItem={({ item }) => (
<NudgeCard nudge={item} {...{ onOpenNudge }} />
)}
/>
)
}
return (
<View style={styles.container}>
{inner}
</View>
)
}
You can pass a callback as a navigation param when you navigate to the ChatDetails screen:
So, instead of
console.log()
, do yourfetch()
or/and whatever you want.