feat: Implement client-side caching for conversations in useMessaging to reduce re-fetching and improve performance.
This commit is contained in:
@@ -49,16 +49,22 @@ interface UseMessagingReturn {
|
||||
hasMoreMessages: boolean;
|
||||
}
|
||||
|
||||
// Module-level cache to avoid re-fetching on tab switch
|
||||
let _cachedConversations: Conversation[] | null = null;
|
||||
let _cachedTimestamp = 0;
|
||||
const CACHE_TTL = 30000; // 30 seconds
|
||||
|
||||
export function useMessaging(options: UseMessagingOptions = {}): UseMessagingReturn {
|
||||
const { autoConnect = true } = options;
|
||||
const { data: session } = useSession();
|
||||
|
||||
// State
|
||||
const [conversations, setConversations] = useState<Conversation[]>([]);
|
||||
// State — initialize from cache if available and fresh
|
||||
const hasFreshCache = _cachedConversations && (Date.now() - _cachedTimestamp < CACHE_TTL);
|
||||
const [conversations, setConversations] = useState<Conversation[]>(hasFreshCache ? _cachedConversations! : []);
|
||||
const [currentConversation, setCurrentConversation] = useState<Conversation | null>(null);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(!hasFreshCache);
|
||||
const [isLoadingMessages, setIsLoadingMessages] = useState(false);
|
||||
const [typingUsers, setTypingUsers] = useState<Set<string>>(new Set());
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
@@ -109,6 +115,9 @@ export function useMessaging(options: UseMessagingOptions = {}): UseMessagingRet
|
||||
try {
|
||||
const data = await messagesService.getConversations();
|
||||
setConversations(data);
|
||||
// Update module-level cache
|
||||
_cachedConversations = data;
|
||||
_cachedTimestamp = Date.now();
|
||||
} catch (error) {
|
||||
console.error('Failed to load conversations:', error);
|
||||
} finally {
|
||||
@@ -557,7 +566,13 @@ export function useMessaging(options: UseMessagingOptions = {}): UseMessagingRet
|
||||
if (autoConnect && isAuthenticated && !isInitializedRef.current) {
|
||||
isInitializedRef.current = true;
|
||||
connect();
|
||||
|
||||
// Only fetch conversations if cache is stale or empty
|
||||
if (!_cachedConversations || Date.now() - _cachedTimestamp >= CACHE_TTL) {
|
||||
loadConversations();
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
// Get initial unread count
|
||||
messagesService.getUnreadCount().then(setUnreadCount).catch(console.error);
|
||||
|
||||
Reference in New Issue
Block a user