Skip to content

Commit a51dbd4

Browse files
committed
feat: move fetching reactions to llc
1 parent c001eeb commit a51dbd4

File tree

5 files changed

+39
-48
lines changed

5 files changed

+39
-48
lines changed

Diff for: package/src/components/MessageMenu/hooks/useFetchReactions.ts

+25-36
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { ReactionResponse, ReactionSort } from 'stream-chat';
44

55
import { MessageType } from '../../../components/MessageList/hooks/useMessageList';
66
import { useChatContext } from '../../../contexts/chatContext/ChatContext';
7-
import { getReactionsForFilterSort } from '../../../store/apis/getReactionsforFilterSort';
87

98
export type UseFetchReactionParams = {
109
limit?: number;
@@ -29,65 +28,55 @@ export const useFetchReactions = ({
2928
const sortString = useMemo(() => JSON.stringify(sort), [sort]);
3029

3130
const fetchReactions = useCallback(async () => {
32-
const loadOfflineReactions = async () => {
33-
if (!messageId) {
34-
return;
35-
}
36-
const reactionsFromDB = await getReactionsForFilterSort({
37-
currentMessageId: messageId,
38-
filters: reactionType ? { type: reactionType } : {},
39-
limit,
40-
sort,
41-
});
42-
if (reactionsFromDB) {
43-
setReactions(reactionsFromDB);
44-
setLoading(false);
45-
}
46-
};
47-
48-
const loadOnlineReactions = async () => {
49-
if (!messageId) {
50-
return;
51-
}
31+
if (!messageId) {
32+
return;
33+
}
34+
try {
5235
const response = await client.queryReactions(
5336
messageId,
5437
reactionType ? { type: reactionType } : {},
5538
sort,
5639
{ limit, next },
5740
);
5841
if (response) {
42+
setReactions((prevReactions) =>
43+
next ? [...prevReactions, ...response.reactions] : response.reactions,
44+
);
5945
setNext(response.next);
60-
setReactions((prevReactions) => [...prevReactions, ...response.reactions]);
6146
setLoading(false);
6247
}
63-
};
64-
65-
try {
66-
// TODO: Threads are not supported for the offline use case as we don't store the thread messages currently, and this will change in the future.
67-
if (enableOfflineSupport && !message?.parent_id) {
68-
await loadOfflineReactions();
69-
} else {
70-
await loadOnlineReactions();
71-
}
7248
} catch (error) {
7349
console.log('Error fetching reactions: ', error);
7450
}
7551
// eslint-disable-next-line react-hooks/exhaustive-deps
76-
}, [client, messageId, reactionType, sortString, next, enableOfflineSupport]);
52+
}, [client, messageId, reactionType, sortString, next, limit, enableOfflineSupport]);
7753

7854
const loadNextPage = useCallback(async () => {
7955
if (next) {
8056
await fetchReactions();
8157
}
82-
// eslint-disable-next-line react-hooks/exhaustive-deps
83-
}, [fetchReactions]);
58+
}, [fetchReactions, next]);
8459

8560
useEffect(() => {
8661
setReactions([]);
8762
setNext(undefined);
8863
fetchReactions();
89-
// eslint-disable-next-line react-hooks/exhaustive-deps
90-
}, [messageId, reactionType, sortString]);
64+
}, [fetchReactions, messageId, reactionType, sortString]);
65+
66+
useEffect(() => {
67+
const listener = client.on('offline_reactions.queried', (event) => {
68+
const { offlineReactions } = event;
69+
if (offlineReactions) {
70+
setReactions(offlineReactions);
71+
setLoading(false);
72+
setNext(undefined);
73+
}
74+
});
75+
76+
return () => {
77+
listener?.unsubscribe();
78+
};
79+
}, [client]);
9180

9281
return { loading, loadNextPage, reactions };
9382
};

Diff for: package/src/store/OfflineDB.ts

+2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ export class OfflineDB extends AbstractOfflineDB {
4747
getAppSettings = ({ userId }: GetAppSettingsType) =>
4848
api.getAppSettings({ currentUserId: userId });
4949

50+
getReactions = api.getReactionsForFilterSort;
51+
5052
addPendingTask = api.addPendingTask;
5153

5254
deletePendingTask = api.deletePendingTask;

Diff for: package/src/store/apis/getReactionsforFilterSort.ts

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ReactionResponse, ReactionSort } from 'stream-chat';
1+
import type { ReactionFilters, ReactionResponse, ReactionSort } from 'stream-chat';
22

33
import { getReactions } from './getReactions';
44
import { selectReactionsForMessages } from './queries/selectReactionsForMessages';
@@ -13,13 +13,13 @@ import { SqliteClient } from '../SqliteClient';
1313
* @param limit The limit of how many reactions should be returned.
1414
*/
1515
export const getReactionsForFilterSort = async ({
16-
currentMessageId,
16+
messageId,
1717
filters,
1818
sort,
1919
limit,
2020
}: {
21-
currentMessageId: string;
22-
filters?: { type?: string };
21+
messageId: string;
22+
filters?: Pick<ReactionFilters, 'type'>;
2323
sort?: ReactionSort;
2424
limit?: number;
2525
}): Promise<ReactionResponse[] | null> => {
@@ -30,7 +30,7 @@ export const getReactionsForFilterSort = async ({
3030

3131
SqliteClient.logger?.('info', 'getReactionsForFilterSort', { filters, sort });
3232

33-
const reactions = await selectReactionsForMessages([currentMessageId], limit, filters, sort);
33+
const reactions = await selectReactionsForMessages([messageId], limit, filters, sort);
3434

3535
if (!reactions) {
3636
return null;
@@ -40,8 +40,5 @@ export const getReactionsForFilterSort = async ({
4040
return [];
4141
}
4242

43-
// const filteredReactions = reactions.filter((reaction) => reaction.type === filters?.type);
44-
// console.log('FILTERED', filteredReactions);
45-
4643
return getReactions({ reactions });
4744
};

Diff for: package/src/store/apis/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export * from './getAppSettings';
88
export * from './getChannelMessages';
99
export * from './getChannels';
1010
export * from './getChannelsForFilterSort';
11+
export * from './getReactionsforFilterSort';
1112
export * from './getLastSyncedAt';
1213
export * from './getMembers';
1314
export * from './getReads';

Diff for: package/src/store/apis/queries/selectReactionsForMessages.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ReactionSort } from 'stream-chat';
1+
import type { ReactionFilters, ReactionSort } from 'stream-chat';
22

33
import { tables } from '../../schema';
44
import { SqliteClient } from '../../SqliteClient';
@@ -14,7 +14,7 @@ import type { TableRowJoinedUser } from '../../types';
1414
export const selectReactionsForMessages = async (
1515
messageIds: string[],
1616
limit: number = 25,
17-
filters?: { type?: string },
17+
filters?: Pick<ReactionFilters, 'type'>,
1818
sort?: ReactionSort,
1919
): Promise<TableRowJoinedUser<'reactions'>[]> => {
2020
const questionMarks = Array(messageIds.length).fill('?').join(',');
@@ -24,12 +24,14 @@ export const selectReactionsForMessages = async (
2424
const userColumnNames = Object.keys(tables.users.columns)
2525
.map((name) => `'${name}', b.${name}`)
2626
.join(', ');
27-
const filterValue = filters?.type ? [filters.type] : [];
27+
const filterValue = filters?.type
28+
? [typeof filters.type === 'string' ? filters.type : filters.type.$eq]
29+
: [];
2830
const createdAtSort = Array.isArray(sort)
2931
? sort.find((s) => !!s.created_at)?.created_at
3032
: sort?.created_at;
3133
const orderByClause = createdAtSort
32-
? `ORDER BY cast(strftime('%s', a.createdAt) AS INTEGER) ${createdAtSort === 1 ? 'DESC' : 'ASC'}`
34+
? `ORDER BY cast(strftime('%s', a.createdAt) AS INTEGER) ${createdAtSort === 1 ? 'ASC' : 'DESC'}`
3335
: '';
3436

3537
SqliteClient.logger?.('info', 'selectReactionsForMessages', {

0 commit comments

Comments
 (0)