@@ -67,6 +67,7 @@ messaging().setBackgroundMessageHandler(async (remoteMessage) => {
6767export const useChatClient = ( ) => {
6868 const [ chatClient , setChatClient ] = useState < StreamChat < StreamChatGenerics > | null > ( null ) ;
6969 const [ isConnecting , setIsConnecting ] = useState ( true ) ;
70+ const [ unreadCount , setUnreadCount ] = useState < number > ( ) ;
7071
7172 const unsubscribePushListenersRef = useRef < ( ) => void > ( ) ;
7273
@@ -81,15 +82,16 @@ export const useChatClient = () => {
8182 timeout : 6000 ,
8283 // logger: (type, msg) => console.log(type, msg)
8384 } ) ;
85+ setChatClient ( client ) ;
8486
8587 const user = {
8688 id : config . userId ,
8789 image : config . userImage ,
8890 name : config . userName ,
8991 } ;
90- const promise = client . connectUser ( user , config . userToken ) ;
91- setChatClient ( client ) ;
92- await promise ;
92+ const connectedUser = await client . connectUser ( user , config . userToken ) ;
93+ const initialUnreadCount = connectedUser ?. me ?. total_unread_count ;
94+ setUnreadCount ( initialUnreadCount ) ;
9395 await AsyncStore . setItem ( '@stream-rn-sampleapp-login-config' , config ) ;
9496
9597 const permissionAuthStatus = await messaging ( ) . hasPermission ( ) ;
@@ -189,11 +191,29 @@ export const useChatClient = () => {
189191 return unsubscribePushListenersRef . current ;
190192 } , [ ] ) ;
191193
194+ /**
195+ * Listen to changes in unread counts and update the badge count
196+ */
197+ useEffect ( ( ) => {
198+ const listener = chatClient ?. on ( ( e ) => {
199+ if ( e . total_unread_count !== undefined ) {
200+ setUnreadCount ( e . total_unread_count ) ;
201+ }
202+ } ) ;
203+
204+ return ( ) => {
205+ if ( listener ) {
206+ listener . unsubscribe ( ) ;
207+ }
208+ } ;
209+ } , [ chatClient ] ) ;
210+
192211 return {
193212 chatClient,
194213 isConnecting,
195214 loginUser,
196215 logout,
197216 switchUser,
217+ unreadCount,
198218 } ;
199219} ;
0 commit comments