Skip to content

Commit c7b82fc

Browse files
committed
fix: broken tests and weird edge cases
1 parent dc3614b commit c7b82fc

File tree

5 files changed

+37
-45
lines changed

5 files changed

+37
-45
lines changed

package/src/__tests__/offline-support/optimistic-update.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ export const OptimisticUpdates = () => {
365365
expect(pendingTasksRows.length).toBe(2);
366366
});
367367

368-
const deleteMessageSpy = jest.spyOn(chatClient, 'deleteMessage').mockImplementation();
368+
const deleteMessageSpy = jest.spyOn(chatClient, '_deleteMessage').mockImplementation();
369369
const sendReactionSpy = jest.spyOn(channel, '_sendReaction').mockImplementation();
370370

371371
act(() => dispatchConnectionChangedEvent(chatClient, true));

package/src/components/Channel/Channel.tsx

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,14 +1037,6 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
10371037
syncingChannelRef.current = true;
10381038
setError(false);
10391039

1040-
if (channelMessagesState?.messages) {
1041-
await channel?.watch({
1042-
messages: {
1043-
limit: channelMessagesState.messages.length + 30,
1044-
},
1045-
});
1046-
}
1047-
10481040
const parseMessage = (message: LocalMessage) =>
10491041
({
10501042
...message,
@@ -1054,6 +1046,14 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
10541046
}) as unknown as MessageResponse;
10551047

10561048
try {
1049+
if (channelMessagesState?.messages) {
1050+
await channel?.watch({
1051+
messages: {
1052+
limit: channelMessagesState.messages.length + 30,
1053+
},
1054+
});
1055+
}
1056+
10571057
if (!thread) {
10581058
copyChannelState();
10591059

package/src/components/Chat/Chat.tsx

Lines changed: 25 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { PropsWithChildren, useEffect, useState } from 'react';
22
import { Image, Platform } from 'react-native';
33

4-
import type { Channel } from 'stream-chat';
4+
import { Channel, OfflineDBState } from 'stream-chat';
55

66
import { useAppSettings } from './hooks/useAppSettings';
77
import { useCreateChatContext } from './hooks/useCreateChatContext';
@@ -20,12 +20,12 @@ import {
2020
DEFAULT_USER_LANGUAGE,
2121
TranslationProvider,
2222
} from '../../contexts/translationContext/TranslationContext';
23+
import { useStateStore } from '../../hooks';
2324
import { useStreami18n } from '../../hooks/useStreami18n';
2425
import init from '../../init';
2526

2627
import { NativeHandlers } from '../../native';
2728
import { OfflineDB } from '../../store/OfflineDB';
28-
import { SqliteClient } from '../../store/SqliteClient';
2929

3030
import type { Streami18n } from '../../utils/i18n/Streami18n';
3131
import { version } from '../../version.json';
@@ -134,6 +134,12 @@ export type ChatProps = Pick<ChatContextValue, 'client'> &
134134
style?: DeepPartial<Theme>;
135135
};
136136

137+
const selector = (nextValue: OfflineDBState) =>
138+
({
139+
initialized: nextValue.initialized,
140+
userId: nextValue.userId,
141+
}) as const;
142+
137143
const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
138144
const {
139145
children,
@@ -157,13 +163,16 @@ const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
157163
*/
158164
const { connectionRecovering, isOnline } = useIsOnline(client, closeConnectionOnBackground);
159165

160-
const [initialisedDatabaseConfig, setInitialisedDatabaseConfig] = useState<{
161-
initialised: boolean;
162-
userID?: string;
163-
}>({
164-
initialised: false,
165-
userID: client.userID,
166-
});
166+
// const [initialisedDatabaseConfig, setInitialisedDatabaseConfig] = useState<{
167+
// initialised: boolean;
168+
// userID?: string;
169+
// }>({
170+
// initialised: false,
171+
// userID: client.userID,
172+
// });
173+
174+
const { initialized: offlineDbInitialized, userId: offlineDbUserId } =
175+
useStateStore(client.offlineDb?.state, selector) ?? {};
167176

168177
/**
169178
* Setup muted user listener
@@ -212,35 +221,18 @@ const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
212221
return;
213222
}
214223

215-
const initializeDatabase = () => {
224+
const initializeDatabase = async () => {
216225
// TODO: Rethink this, it looks ugly
217226
if (!client.offlineDb) {
218227
client.setOfflineDBApi(new OfflineDB({ client }));
219228
}
220-
// This acts as a lock for some very rare occurrences of concurrency
221-
// issues we've encountered before with the QuickSqliteClient being
222-
// uninitialized before it's being invoked.
223-
setInitialisedDatabaseConfig({ initialised: false, userID });
224-
SqliteClient.initializeDatabase()
225-
.then(async () => {
226-
setInitialisedDatabaseConfig({ initialised: true, userID });
227-
if (client.offlineDb) {
228-
await client.offlineDb?.syncManager.init();
229-
// client.offlineDb.initialised = initialised;
230-
}
231-
})
232-
.catch((error) => {
233-
console.log('Error Initializing DB:', error);
234-
});
235-
};
236229

237-
initializeDatabase();
238-
239-
return () => {
240-
if (userID && enableOfflineSupport) {
241-
// SqliteClient.closeDB();
230+
if (client.offlineDb) {
231+
await client.offlineDb.init(userID);
242232
}
243233
};
234+
235+
initializeDatabase();
244236
// eslint-disable-next-line react-hooks/exhaustive-deps
245237
}, [userID, enableOfflineSupport]);
246238

@@ -258,12 +250,11 @@ const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
258250
// In case something went wrong, make sure to also unsubscribe the listener
259251
// on unmount if it exists to prevent a memory leak.
260252
// FIXME: Should be wrapped in its own unregistration mechanism
261-
client.offlineDb?.syncManager.connectionChangedListener?.unsubscribe();
253+
// client.offlineDb?.syncManager.connectionChangedListener?.unsubscribe();
262254
};
263255
}, [client]);
264256

265-
const initialisedDatabase =
266-
initialisedDatabaseConfig.initialised && userID === initialisedDatabaseConfig.userID;
257+
const initialisedDatabase = !!offlineDbInitialized && userID === offlineDbUserId;
267258

268259
const appSettings = useAppSettings(client, isOnline, enableOfflineSupport, initialisedDatabase);
269260

package/src/components/Chat/__tests__/Chat.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,8 @@ describe('TranslationContext', () => {
255255
rerender(<Chat client={chatClientWithUser} enableOfflineSupport key={2} />);
256256

257257
await waitFor(() => {
258-
expect(initSpy).toHaveBeenCalledTimes(2);
259-
expect(unsubscribeSpy).toHaveBeenCalledTimes(2);
258+
expect(initSpy).toHaveBeenCalledTimes(1);
259+
expect(unsubscribeSpy).toHaveBeenCalledTimes(0);
260260
expect(chatClientWithUser.listeners['connection.changed'].length).toBe(
261261
listenersAfterInitialMount.length,
262262
);

package/src/store/SqliteClient.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ export class SqliteClient {
165165
await SqliteClient.dropTables();
166166
await SqliteClient.updateUserPragmaVersion(SqliteClient.dbVersion);
167167
}
168+
168169
SqliteClient.logger?.('info', 'create tables if not exists', {
169170
tables: Object.keys(tables),
170171
});

0 commit comments

Comments
 (0)