Skip to content
This repository has been archived by the owner on Oct 4, 2023. It is now read-only.

Commit

Permalink
Fetch chats on app foreground (#3693)
Browse files Browse the repository at this point in the history
  • Loading branch information
piazzatron authored Jul 3, 2023
1 parent 16ca56a commit 210113d
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions packages/mobile/src/screens/chat-screen/ChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useKeyboard } from '@react-native-community/hooks'
import { useFocusEffect } from '@react-navigation/native'
import type { FlatListProps, LayoutChangeEvent } from 'react-native'
import {
AppState,
FlatList,
Keyboard,
Platform,
Expand Down Expand Up @@ -201,6 +202,40 @@ const getNewMessageToastThreshold = (
: NEW_MESSAGE_TOAST_SCROLL_THRESHOLD
}

// Gets latest messages on both initial render and when app state changes
const useGetLatestMessages = (
chatId: string,
dispatch: ReturnType<typeof useDispatch>
) => {
const fetchLatestMessagesCallback = useCallback(() => {
if (chatId) {
dispatch(fetchLatestMessages({ chatId }))
}
}, [dispatch, chatId])

// Refresh messages on first render
useEffect(() => {
console.debug('Fetching latest messages on first render')
fetchLatestMessagesCallback()
}, [fetchLatestMessagesCallback])

// Also listen to app state changes to refresh messages,
// in case this page was previously in the background
useEffect(() => {
const handle = AppState.addEventListener('change', (state) => {
if (state === 'active') {
console.debug(
'App came back from background onto chat page, fetching latest messages'
)
fetchLatestMessagesCallback()
}
})

// Remove listener on unmount
return () => handle.remove()
})
}

export const ChatScreen = () => {
const styles = useStyles()
const palette = useThemePalette()
Expand Down Expand Up @@ -255,12 +290,7 @@ export const ChatScreen = () => {
// The chat/chatId selectors will trigger the rerenders necessary.
const chatFrozenRef = useRef(chat)

// Refresh messages on first render
useEffect(() => {
if (chatId) {
dispatch(fetchLatestMessages({ chatId }))
}
}, [dispatch, chatId])
useGetLatestMessages(chatId, dispatch)

useEffect(() => {
// Update chatFrozenRef when entering a new chat screen.
Expand Down

0 comments on commit 210113d

Please sign in to comment.