fixed code
This commit is contained in:
@@ -6,7 +6,15 @@ export function UnreadProvider({ children }) {
|
||||
const [unreadMap, setUnreadMap] = useState({});
|
||||
|
||||
const setChatUnread = useCallback((chatId, count) => {
|
||||
setUnreadMap(prev => ({ ...prev, [chatId]: count }));
|
||||
setUnreadMap(prev => {
|
||||
if (count > 0) {
|
||||
return { ...prev, [chatId]: count };
|
||||
}
|
||||
if (prev[chatId] === undefined) return prev;
|
||||
const next = { ...prev };
|
||||
delete next[chatId];
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clearChatUnread = useCallback((chatId) => {
|
||||
@@ -18,6 +26,11 @@ export function UnreadProvider({ children }) {
|
||||
});
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Инициализирует/синхронизирует unreadMap из полного списка чатов
|
||||
* (например, при первой загрузке через REST). Ожидает ПОЛНЫЙ список —
|
||||
* чаты, отсутствующие в переданном массиве, не трогает.
|
||||
*/
|
||||
const updateFromChats = useCallback((chats) => {
|
||||
setUnreadMap(prev => {
|
||||
const next = { ...prev };
|
||||
@@ -25,6 +38,8 @@ export function UnreadProvider({ children }) {
|
||||
const count = chat.unreadCount ?? chat.unreadMessages ?? 0;
|
||||
if (count > 0) {
|
||||
next[chat.id] = count;
|
||||
} else {
|
||||
delete next[chat.id];
|
||||
}
|
||||
}
|
||||
return next;
|
||||
@@ -32,14 +47,14 @@ export function UnreadProvider({ children }) {
|
||||
}, []);
|
||||
|
||||
const totalUnread = useMemo(() =>
|
||||
Object.values(unreadMap).reduce((sum, c) => sum + c, 0),
|
||||
[unreadMap]
|
||||
Object.values(unreadMap).reduce((sum, c) => sum + c, 0),
|
||||
[unreadMap]
|
||||
);
|
||||
|
||||
return (
|
||||
<UnreadContext.Provider value={{ unreadMap, totalUnread, setChatUnread, clearChatUnread, updateFromChats }}>
|
||||
{children}
|
||||
</UnreadContext.Provider>
|
||||
<UnreadContext.Provider value={{ unreadMap, totalUnread, setChatUnread, clearChatUnread, updateFromChats }}>
|
||||
{children}
|
||||
</UnreadContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,4 +62,4 @@ export function useUnread() {
|
||||
const ctx = useContext(UnreadContext);
|
||||
if (!ctx) throw new Error('useUnread must be used within UnreadProvider');
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user