From 4d87b32fce89bfd08561d85a3f5440a98131336c Mon Sep 17 00:00:00 2001
From: Ivan Chen <ivan@tagg.id>
Date: Fri, 9 Apr 2021 19:05:57 -0400
Subject: fixed unread

---
 src/components/messages/MessagesHeader.tsx | 29 ++++++++++++++++++++++++-----
 1 file changed, 24 insertions(+), 5 deletions(-)

(limited to 'src/components/messages/MessagesHeader.tsx')

diff --git a/src/components/messages/MessagesHeader.tsx b/src/components/messages/MessagesHeader.tsx
index 660da97d..1bd9b55a 100644
--- a/src/components/messages/MessagesHeader.tsx
+++ b/src/components/messages/MessagesHeader.tsx
@@ -1,10 +1,10 @@
-import React, {Fragment, useContext} from 'react';
+import React, {Fragment, useContext, useEffect, useState} from 'react';
 import {StyleSheet, View} from 'react-native';
 import {Text} from 'react-native-animatable';
 import {TouchableOpacity} from 'react-native-gesture-handler';
-import {normalize} from '../../utils';
-import ComposeIcon from '../../assets/icons/compose.svg';
 import {ChatContext} from '../../App';
+import ComposeIcon from '../../assets/icons/compose.svg';
+import {normalize} from '../../utils';
 
 type MessagesHeaderProps = {
   createChannel: () => void;
@@ -12,11 +12,30 @@ type MessagesHeaderProps = {
 
 const MessagesHeader: React.FC<MessagesHeaderProps> = ({createChannel}) => {
   const {chatClient} = useContext(ChatContext);
-  const unread = chatClient.user?.total_unread_count as number;
+  const [unread, setUnread] = useState(0);
+
+  useEffect(() => {
+    const newCount = chatClient.user?.total_unread_count as number;
+    if (newCount) {
+      setUnread(newCount);
+    }
+    const listener = chatClient?.on((e) => {
+      if (e.total_unread_count) {
+        setUnread(e.total_unread_count);
+      }
+    });
+
+    return () => {
+      if (listener) {
+        listener.unsubscribe();
+      }
+    };
+  }, [chatClient]);
+
   return (
     <View style={styles.header}>
       <Text style={styles.headerText}>Messages</Text>
-      {unread && unread !== 0 ? (
+      {unread !== 0 ? (
         <Text style={styles.unreadText}>
           {unread > 99 ? '99+' : unread} unread
         </Text>
-- 
cgit v1.2.3-70-g09d2

