stream-chat-react-native-core 5.15.0-beta.4 → 5.15.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,8 +15,7 @@ var _useIsMountedRef = require("../../../hooks/useIsMountedRef");
15
15
  var _getChannelsForFilterSort = require("../../../store/apis/getChannelsForFilterSort");
16
16
  var _date = require("../../../utils/date");
17
17
  var _DBSyncManager = require("../../../utils/DBSyncManager");
18
- var _utils = require("../../../utils/utils");
19
- var _utils2 = require("../utils");
18
+ var _utils = require("../utils");
20
19
  var waitSeconds = function waitSeconds(seconds) {
21
20
  return new Promise(function (resolve) {
22
21
  setTimeout(resolve, seconds * _date.ONE_SECOND_IN_MS);
@@ -74,12 +73,7 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
74
73
  isQueryStale,
75
74
  currentRequestId,
76
75
  newOptions,
77
- failedMessagesInDb,
78
- cid,
79
- failedMessages,
80
76
  channelQueryResponse,
81
- _cid2,
82
- msgsToAdd,
83
77
  newChannels,
84
78
  _args = arguments;
85
79
  return _regenerator["default"].wrap(function _callee$(_context) {
@@ -115,35 +109,22 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
115
109
  currentRequestId = activeRequestId.current;
116
110
  setActiveQueryType(queryType);
117
111
  newOptions = (0, _extends2["default"])({
118
- limit: (_options$limit = options == null ? void 0 : options.limit) != null ? _options$limit : _utils2.MAX_QUERY_CHANNELS_LIMIT,
112
+ limit: (_options$limit = options == null ? void 0 : options.limit) != null ? _options$limit : _utils.MAX_QUERY_CHANNELS_LIMIT,
119
113
  offset: queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0
120
114
  }, options);
121
115
  _context.prev = 17;
122
- failedMessagesInDb = new Map();
123
- if (enableOfflineSupport) {
124
- for (cid in client.activeChannels) {
125
- failedMessages = getFailedMessages(client.activeChannels[cid]);
126
- if (failedMessages) failedMessagesInDb.set(cid, failedMessages);
127
- }
128
- }
129
- _context.next = 22;
116
+ _context.next = 20;
130
117
  return client.queryChannels(filters, sort, newOptions, {
131
- skipInitialization: activeChannels.current
118
+ skipInitialization: enableOfflineSupport ? undefined : activeChannels.current
132
119
  });
133
- case 22:
120
+ case 20:
134
121
  channelQueryResponse = _context.sent;
135
122
  if (!(isQueryStale() || !isMountedRef.current)) {
136
- _context.next = 25;
123
+ _context.next = 23;
137
124
  break;
138
125
  }
139
126
  return _context.abrupt("return");
140
- case 25:
141
- if (failedMessagesInDb.size) {
142
- for (_cid2 in client.activeChannels) {
143
- msgsToAdd = failedMessagesInDb.get(_cid2);
144
- if (msgsToAdd) client.activeChannels[_cid2].state.addMessagesSorted(msgsToAdd);
145
- }
146
- }
127
+ case 23:
147
128
  newChannels = queryType === 'loadChannels' && !staticChannelsActive && channels ? [].concat((0, _toConsumableArray2["default"])(channels), (0, _toConsumableArray2["default"])(channelQueryResponse)) : channelQueryResponse.map(function (c) {
148
129
  var existingChannel = client.activeChannels[c.cid];
149
130
  if (existingChannel) {
@@ -155,38 +136,38 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
155
136
  setStaticChannelsActive(false);
156
137
  setHasNextPage(channelQueryResponse.length >= newOptions.limit);
157
138
  isQueryingRef.current = false;
158
- _context.next = 46;
139
+ _context.next = 43;
159
140
  break;
160
- case 33:
161
- _context.prev = 33;
141
+ case 30:
142
+ _context.prev = 30;
162
143
  _context.t0 = _context["catch"](17);
163
144
  isQueryingRef.current = false;
164
- _context.next = 38;
145
+ _context.next = 35;
165
146
  return waitSeconds(2);
166
- case 38:
147
+ case 35:
167
148
  if (!isQueryStale()) {
168
- _context.next = 40;
149
+ _context.next = 37;
169
150
  break;
170
151
  }
171
152
  return _context.abrupt("return");
172
- case 40:
153
+ case 37:
173
154
  if (!(retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current)) {
174
- _context.next = 45;
155
+ _context.next = 42;
175
156
  break;
176
157
  }
177
158
  setActiveQueryType(null);
178
159
  console.warn(_context.t0);
179
160
  setError(new Error("Maximum number of retries reached in queryChannels. Last error message is: " + _context.t0));
180
161
  return _context.abrupt("return");
181
- case 45:
162
+ case 42:
182
163
  return _context.abrupt("return", queryChannels(queryType, retryCount + 1));
183
- case 46:
164
+ case 43:
184
165
  setActiveQueryType(null);
185
- case 47:
166
+ case 44:
186
167
  case "end":
187
168
  return _context.stop();
188
169
  }
189
- }, _callee, null, [[17, 33]]);
170
+ }, _callee, null, [[17, 30]]);
190
171
  }));
191
172
  return function queryChannels() {
192
173
  return _ref2.apply(this, arguments);
@@ -238,9 +219,11 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
238
219
  sort: sort
239
220
  });
240
221
  if (channelsFromDB) {
241
- setChannels(client.hydrateActiveChannels(channelsFromDB, {
242
- offlineMode: true
243
- }));
222
+ var offlineChannels = client.hydrateActiveChannels(channelsFromDB, {
223
+ offlineMode: true,
224
+ skipInitialization: []
225
+ });
226
+ setChannels(offlineChannels);
244
227
  setStaticChannelsActive(true);
245
228
  }
246
229
  } catch (e) {
@@ -309,19 +292,4 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
309
292
  };
310
293
  };
311
294
  exports.usePaginatedChannels = usePaginatedChannels;
312
- function getFailedMessages(channel) {
313
- var failedMsgs = channel.state.messages.filter(function (m) {
314
- return m.status === _utils.MessageStatusTypes.FAILED;
315
- });
316
- if (failedMsgs.length) {
317
- return failedMsgs.map(function (m) {
318
- return (0, _extends2["default"])({}, m, {
319
- created_at: m.created_at.toISOString(),
320
- pinned_at: m.pinned_at ? m.pinned_at.toISOString() : null,
321
- updated_at: m.updated_at.toISOString()
322
- });
323
- });
324
- }
325
- return undefined;
326
- }
327
295
  //# sourceMappingURL=usePaginatedChannels.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_ActiveChannelsRefContext","_ChatContext","_useIsMountedRef","_getChannelsForFilterSort","_date","_DBSyncManager","_utils","_utils2","waitSeconds","seconds","Promise","resolve","setTimeout","ONE_SECOND_IN_MS","DEFAULT_OPTIONS","message_limit","MAX_NUMBER_OF_RETRIES","RETRY_INTERVAL_IN_MS","usePaginatedChannels","_ref","enableOfflineSupport","_ref$filters","filters","_ref$options","options","setForceUpdate","_ref$sort","sort","_useState","useState","_useState2","_slicedToArray2","channels","setChannels","_useState3","undefined","_useState4","error","setError","_useState5","_useState6","staticChannelsActive","setStaticChannelsActive","_useState7","_useState8","activeQueryType","setActiveQueryType","_useState9","_useState10","hasNextPage","setHasNextPage","activeChannels","useActiveChannelsRefContext","isMountedRef","useIsMountedRef","_useChatContext","useChatContext","client","filtersRef","useRef","sortRef","activeRequestId","isQueryingRef","lastRefresh","Date","now","queryChannels","_ref2","_asyncToGenerator2","_regenerator","mark","_callee","_options$limit","queryType","retryCount","hasUpdatedData","isQueryStale","currentRequestId","newOptions","failedMessagesInDb","cid","failedMessages","channelQueryResponse","_cid2","msgsToAdd","newChannels","_args","arguments","wrap","_callee$","_context","prev","next","length","current","abrupt","JSON","stringify","some","Boolean","_extends2","limit","MAX_QUERY_CHANNELS_LIMIT","offset","Map","getFailedMessages","set","skipInitialization","sent","size","get","state","addMessagesSorted","concat","_toConsumableArray2","map","c","existingChannel","t0","console","warn","Error","stop","apply","refreshList","_ref3","_callee2","_callee2$","_context2","reloadList","filterStr","useMemo","sortStr","useEffect","loadOfflineChannels","_client$user","user","id","channelsFromDB","getChannelsForFilterSort","currentUserId","hydrateActiveChannels","offlineMode","e","listener","DBSyncManager","onSyncStatusChange","syncStatus","dbSyncStatus","getSyncStatus","on","_ref4","_callee3","event","_callee3$","_context3","online","u","_x","_listener","unsubscribe","loadingChannels","loadingNextPage","loadNextPage","refreshing","exports","channel","failedMsgs","messages","filter","m","status","MessageStatusTypes","FAILED","created_at","toISOString","pinned_at","updated_at"],"sources":["usePaginatedChannels.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport type {\n Channel,\n ChannelFilters,\n ChannelOptions,\n ChannelSort,\n MessageResponse,\n} from 'stream-chat';\n\nimport { useActiveChannelsRefContext } from '../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext';\nimport { useChatContext } from '../../../contexts/chatContext/ChatContext';\nimport { useIsMountedRef } from '../../../hooks/useIsMountedRef';\n\nimport { getChannelsForFilterSort } from '../../../store/apis/getChannelsForFilterSort';\nimport type { DefaultStreamChatGenerics } from '../../../types/types';\nimport { ONE_SECOND_IN_MS } from '../../../utils/date';\nimport { DBSyncManager } from '../../../utils/DBSyncManager';\nimport { MessageStatusTypes } from '../../../utils/utils';\nimport { MAX_QUERY_CHANNELS_LIMIT } from '../utils';\n\nconst waitSeconds = (seconds: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, seconds * ONE_SECOND_IN_MS);\n });\n\ntype Parameters<StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics> =\n {\n enableOfflineSupport: boolean;\n filters: ChannelFilters<StreamChatGenerics>;\n options: ChannelOptions;\n setForceUpdate: React.Dispatch<React.SetStateAction<number>>;\n sort: ChannelSort<StreamChatGenerics>;\n };\n\nconst DEFAULT_OPTIONS = {\n message_limit: 10,\n};\n\nconst MAX_NUMBER_OF_RETRIES = 3;\nconst RETRY_INTERVAL_IN_MS = 5000;\n\ntype QueryType = 'queryLocalDB' | 'reload' | 'refresh' | 'loadChannels';\n\nexport type QueryChannels = (queryType?: QueryType, retryCount?: number) => Promise<void>;\n\nexport const usePaginatedChannels = <\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>({\n enableOfflineSupport,\n filters = {},\n options = DEFAULT_OPTIONS,\n setForceUpdate,\n sort = {},\n}: Parameters<StreamChatGenerics>) => {\n const [channels, setChannels] = useState<Channel<StreamChatGenerics>[] | null>(null);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [staticChannelsActive, setStaticChannelsActive] = useState<boolean>(false);\n const [activeQueryType, setActiveQueryType] = useState<QueryType | null>('queryLocalDB');\n const [hasNextPage, setHasNextPage] = useState<boolean>(false);\n const activeChannels = useActiveChannelsRefContext();\n const isMountedRef = useIsMountedRef();\n const { client } = useChatContext<StreamChatGenerics>();\n\n const filtersRef = useRef<typeof filters | null>(null);\n const sortRef = useRef<typeof sort | null>(null);\n const activeRequestId = useRef<number>(0);\n const isQueryingRef = useRef(false);\n const lastRefresh = useRef(Date.now());\n\n const queryChannels: QueryChannels = async (\n queryType: QueryType = 'loadChannels',\n retryCount = 0,\n ): Promise<void> => {\n if (!client || !isMountedRef.current) return;\n\n const hasUpdatedData =\n queryType === 'loadChannels' ||\n queryType === 'refresh' ||\n [\n JSON.stringify(filtersRef.current) !== JSON.stringify(filters),\n JSON.stringify(sortRef.current) !== JSON.stringify(sort),\n ].some(Boolean);\n\n const isQueryStale = () => !isMountedRef || activeRequestId.current !== currentRequestId;\n\n /**\n * We don't need to make another call to query channels if we don't\n * have new data for the query to include\n * */\n if (!hasUpdatedData) {\n if (activeQueryType === null) return;\n }\n\n filtersRef.current = filters;\n sortRef.current = sort;\n isQueryingRef.current = true;\n setError(undefined);\n activeRequestId.current++;\n const currentRequestId = activeRequestId.current;\n setActiveQueryType(queryType);\n\n const newOptions = {\n limit: options?.limit ?? MAX_QUERY_CHANNELS_LIMIT,\n offset:\n queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0,\n ...options,\n };\n\n try {\n // If failed messages were present in DB it would be in the channel state now and be overwritten by the queryChannels call\n // So we store them in a separate object and add them back to the channel state after the queryChannels call\n const failedMessagesInDb: Map<string, MessageResponse<StreamChatGenerics>[]> = new Map();\n if (enableOfflineSupport) {\n for (const cid in client.activeChannels) {\n const failedMessages = getFailedMessages(client.activeChannels[cid]);\n if (failedMessages) failedMessagesInDb.set(cid, failedMessages);\n }\n }\n\n /**\n * We skipInitialization here for handling race condition between ChannelList, Channel (and Thread)\n * when they all (may) update the channel state at the same time (when connection state recovers)\n * TODO: if we move the channel state to a single context and share it between ChannelList, Channel and Thread we can remove this\n */\n const channelQueryResponse = await client.queryChannels(filters, sort, newOptions, {\n skipInitialization: activeChannels.current,\n });\n if (isQueryStale() || !isMountedRef.current) {\n return;\n }\n\n if (failedMessagesInDb.size) {\n for (const cid in client.activeChannels) {\n const msgsToAdd = failedMessagesInDb.get(cid);\n if (msgsToAdd) client.activeChannels[cid].state.addMessagesSorted(msgsToAdd);\n }\n }\n\n const newChannels =\n queryType === 'loadChannels' && !staticChannelsActive && channels\n ? [...channels, ...channelQueryResponse]\n : channelQueryResponse.map((c) => {\n const existingChannel = client.activeChannels[c.cid];\n if (existingChannel) {\n return existingChannel;\n }\n\n return c;\n });\n\n setChannels(newChannels);\n setStaticChannelsActive(false);\n setHasNextPage(channelQueryResponse.length >= newOptions.limit);\n isQueryingRef.current = false;\n } catch (err: unknown) {\n isQueryingRef.current = false;\n await waitSeconds(2);\n\n if (isQueryStale()) {\n return;\n }\n\n // querying.current check is needed in order to make sure the next query call doesnt flick an error\n // state and then succeed (reconnect case)\n if (retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current) {\n setActiveQueryType(null);\n console.warn(err);\n\n setError(\n new Error(\n `Maximum number of retries reached in queryChannels. Last error message is: ${err}`,\n ),\n );\n return;\n }\n\n return queryChannels(queryType, retryCount + 1);\n }\n\n setActiveQueryType(null);\n };\n\n const refreshList = async () => {\n const now = Date.now();\n // Only allow pull-to-refresh 5 seconds after last successful refresh.\n if (now - lastRefresh.current < RETRY_INTERVAL_IN_MS && error === undefined) {\n return;\n }\n\n lastRefresh.current = Date.now();\n await queryChannels('refresh');\n };\n\n const reloadList = () => queryChannels('reload');\n\n /**\n * Equality check using stringified filters/sort ensure that we don't make un-necessary queryChannels api calls\n * for the scenario:\n *\n * <ChannelList\n * filters={{\n * members: { $in: ['vishal'] }\n * }}\n * ...\n * />\n *\n * Here we have passed filters as inline object, which means on every re-render of\n * parent component, ChannelList will receive new object reference (even though value is same), which\n * in return will trigger useEffect. To avoid this, we can add a value check.\n */\n const filterStr = useMemo(() => JSON.stringify(filters), [filters]);\n const sortStr = useMemo(() => JSON.stringify(sort), [sort]);\n\n useEffect(() => {\n const loadOfflineChannels = () => {\n if (!client?.user?.id) return;\n\n try {\n const channelsFromDB = getChannelsForFilterSort({\n currentUserId: client.user.id,\n filters,\n sort,\n });\n\n if (channelsFromDB) {\n setChannels(\n client.hydrateActiveChannels(channelsFromDB, {\n offlineMode: true,\n }),\n );\n setStaticChannelsActive(true);\n }\n } catch (e) {\n console.warn('Failed to get channels from database: ', e);\n }\n\n setActiveQueryType(null);\n };\n\n let listener: ReturnType<typeof DBSyncManager.onSyncStatusChange>;\n if (enableOfflineSupport) {\n // Any time DB is synced, we need to update the UI with local DB channels first,\n // and then call queryChannels to ensure any new channels are added to UI.\n listener = DBSyncManager.onSyncStatusChange((syncStatus) => {\n if (syncStatus) {\n loadOfflineChannels();\n reloadList();\n }\n });\n // On start, load the channels from local db.\n loadOfflineChannels();\n\n // If db is already synced (sync api and pending api calls), then\n // right away call queryChannels.\n const dbSyncStatus = DBSyncManager.getSyncStatus();\n if (dbSyncStatus) {\n reloadList();\n }\n } else {\n listener = client.on('connection.changed', async (event) => {\n if (event.online) {\n await refreshList();\n setForceUpdate((u) => u + 1);\n }\n });\n\n reloadList();\n }\n\n return () => listener?.unsubscribe?.();\n }, [filterStr, sortStr]);\n\n return {\n channels,\n error,\n hasNextPage,\n loadingChannels:\n activeQueryType === 'queryLocalDB'\n ? true\n : (activeQueryType === 'reload' || activeQueryType === null) && channels === null,\n loadingNextPage: activeQueryType === 'loadChannels',\n loadNextPage: queryChannels,\n refreshing: activeQueryType === 'refresh',\n refreshList,\n reloadList,\n // Although channels can be null, there is no practical case where channels will be null\n // when setChannels is used. setChannels is only recommended to be used for overriding\n // event handler. Thus instead of adding if check for channels === null, its better to\n // simply reassign types here.\n setChannels,\n staticChannelsActive,\n };\n};\n\nfunction getFailedMessages<\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>(channel: Channel<StreamChatGenerics>): MessageResponse<StreamChatGenerics>[] | undefined {\n const failedMsgs = channel.state.messages.filter((m) => m.status === MessageStatusTypes.FAILED);\n if (failedMsgs.length) {\n return failedMsgs.map(\n (m) =>\n ({\n ...m,\n created_at: m.created_at.toISOString(),\n pinned_at: m.pinned_at ? m.pinned_at.toISOString() : null,\n updated_at: m.updated_at.toISOString(),\n } as MessageResponse<StreamChatGenerics>),\n );\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,yBAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAEA,IAAAI,yBAAA,GAAAJ,OAAA;AAEA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,cAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AACA,IAAAQ,OAAA,GAAAR,OAAA;AAEA,IAAMS,WAAW,GAAG,SAAdA,WAAWA,CAAIC,OAAe;EAAA,OAClC,IAAIC,OAAO,CAAC,UAACC,OAAO,EAAK;IACvBC,UAAU,CAACD,OAAO,EAAEF,OAAO,GAAGI,sBAAgB,CAAC;EACjD,CAAC,CAAC;AAAA;AAWJ,IAAMC,eAAe,GAAG;EACtBC,aAAa,EAAE;AACjB,CAAC;AAED,IAAMC,qBAAqB,GAAG,CAAC;AAC/B,IAAMC,oBAAoB,GAAG,IAAI;AAM1B,IAAMC,oBAAoB,GAAG,SAAvBA,oBAAoBA,CAAAC,IAAA,EAQK;EAAA,IALpCC,oBAAoB,GAAAD,IAAA,CAApBC,oBAAoB;IAAAC,YAAA,GAAAF,IAAA,CACpBG,OAAO;IAAPA,OAAO,GAAAD,YAAA,cAAG,CAAC,CAAC,GAAAA,YAAA;IAAAE,YAAA,GAAAJ,IAAA,CACZK,OAAO;IAAPA,OAAO,GAAAD,YAAA,cAAGT,eAAe,GAAAS,YAAA;IACzBE,cAAc,GAAAN,IAAA,CAAdM,cAAc;IAAAC,SAAA,GAAAP,IAAA,CACdQ,IAAI;IA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AAE;IAAA,CACC,CAC5C;EACH;EACA,OAAO5I,SAAS;AAClB"}
1
+ {"version":3,"names":["_react","require","_ActiveChannelsRefContext","_ChatContext","_useIsMountedRef","_getChannelsForFilterSort","_date","_DBSyncManager","_utils","waitSeconds","seconds","Promise","resolve","setTimeout","ONE_SECOND_IN_MS","DEFAULT_OPTIONS","message_limit","MAX_NUMBER_OF_RETRIES","RETRY_INTERVAL_IN_MS","usePaginatedChannels","_ref","enableOfflineSupport","_ref$filters","filters","_ref$options","options","setForceUpdate","_ref$sort","sort","_useState","useState","_useState2","_slicedToArray2","channels","setChannels","_useState3","undefined","_useState4","error","setError","_useState5","_useState6","staticChannelsActive","setStaticChannelsActive","_useState7","_useState8","activeQueryType","setActiveQueryType","_useState9","_useState10","hasNextPage","setHasNextPage","activeChannels","useActiveChannelsRefContext","isMountedRef","useIsMountedRef","_useChatContext","useChatContext","client","filtersRef","useRef","sortRef","activeRequestId","isQueryingRef","lastRefresh","Date","now","queryChannels","_ref2","_asyncToGenerator2","_regenerator","mark","_callee","_options$limit","queryType","retryCount","hasUpdatedData","isQueryStale","currentRequestId","newOptions","channelQueryResponse","newChannels","_args","arguments","wrap","_callee$","_context","prev","next","length","current","abrupt","JSON","stringify","some","Boolean","_extends2","limit","MAX_QUERY_CHANNELS_LIMIT","offset","skipInitialization","sent","concat","_toConsumableArray2","map","c","existingChannel","cid","t0","console","warn","Error","stop","apply","refreshList","_ref3","_callee2","_callee2$","_context2","reloadList","filterStr","useMemo","sortStr","useEffect","loadOfflineChannels","_client$user","user","id","channelsFromDB","getChannelsForFilterSort","currentUserId","offlineChannels","hydrateActiveChannels","offlineMode","e","listener","DBSyncManager","onSyncStatusChange","syncStatus","dbSyncStatus","getSyncStatus","on","_ref4","_callee3","event","_callee3$","_context3","online","u","_x","_listener","unsubscribe","loadingChannels","loadingNextPage","loadNextPage","refreshing","exports"],"sources":["usePaginatedChannels.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport type { Channel, ChannelFilters, ChannelOptions, ChannelSort } from 'stream-chat';\n\nimport { useActiveChannelsRefContext } from '../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext';\nimport { useChatContext } from '../../../contexts/chatContext/ChatContext';\nimport { useIsMountedRef } from '../../../hooks/useIsMountedRef';\n\nimport { getChannelsForFilterSort } from '../../../store/apis/getChannelsForFilterSort';\nimport type { DefaultStreamChatGenerics } from '../../../types/types';\nimport { ONE_SECOND_IN_MS } from '../../../utils/date';\nimport { DBSyncManager } from '../../../utils/DBSyncManager';\nimport { MAX_QUERY_CHANNELS_LIMIT } from '../utils';\n\nconst waitSeconds = (seconds: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, seconds * ONE_SECOND_IN_MS);\n });\n\ntype Parameters<StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics> =\n {\n enableOfflineSupport: boolean;\n filters: ChannelFilters<StreamChatGenerics>;\n options: ChannelOptions;\n setForceUpdate: React.Dispatch<React.SetStateAction<number>>;\n sort: ChannelSort<StreamChatGenerics>;\n };\n\nconst DEFAULT_OPTIONS = {\n message_limit: 10,\n};\n\nconst MAX_NUMBER_OF_RETRIES = 3;\nconst RETRY_INTERVAL_IN_MS = 5000;\n\ntype QueryType = 'queryLocalDB' | 'reload' | 'refresh' | 'loadChannels';\n\nexport type QueryChannels = (queryType?: QueryType, retryCount?: number) => Promise<void>;\n\nexport const usePaginatedChannels = <\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>({\n enableOfflineSupport,\n filters = {},\n options = DEFAULT_OPTIONS,\n setForceUpdate,\n sort = {},\n}: Parameters<StreamChatGenerics>) => {\n const [channels, setChannels] = useState<Channel<StreamChatGenerics>[] | null>(null);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [staticChannelsActive, setStaticChannelsActive] = useState<boolean>(false);\n const [activeQueryType, setActiveQueryType] = useState<QueryType | null>('queryLocalDB');\n const [hasNextPage, setHasNextPage] = useState<boolean>(false);\n const activeChannels = useActiveChannelsRefContext();\n const isMountedRef = useIsMountedRef();\n const { client } = useChatContext<StreamChatGenerics>();\n\n const filtersRef = useRef<typeof filters | null>(null);\n const sortRef = useRef<typeof sort | null>(null);\n const activeRequestId = useRef<number>(0);\n const isQueryingRef = useRef(false);\n const lastRefresh = useRef(Date.now());\n\n const queryChannels: QueryChannels = async (\n queryType: QueryType = 'loadChannels',\n retryCount = 0,\n ): Promise<void> => {\n if (!client || !isMountedRef.current) return;\n\n const hasUpdatedData =\n queryType === 'loadChannels' ||\n queryType === 'refresh' ||\n [\n JSON.stringify(filtersRef.current) !== JSON.stringify(filters),\n JSON.stringify(sortRef.current) !== JSON.stringify(sort),\n ].some(Boolean);\n\n const isQueryStale = () => !isMountedRef || activeRequestId.current !== currentRequestId;\n\n /**\n * We don't need to make another call to query channels if we don't\n * have new data for the query to include\n * */\n if (!hasUpdatedData) {\n if (activeQueryType === null) return;\n }\n\n filtersRef.current = filters;\n sortRef.current = sort;\n isQueryingRef.current = true;\n setError(undefined);\n activeRequestId.current++;\n const currentRequestId = activeRequestId.current;\n setActiveQueryType(queryType);\n\n const newOptions = {\n limit: options?.limit ?? MAX_QUERY_CHANNELS_LIMIT,\n offset:\n queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0,\n ...options,\n };\n\n try {\n /**\n * We skipInitialization here for handling race condition between ChannelList, Channel (and Thread)\n * when they all (may) update the channel state at the same time (when connection state recovers)\n * TODO: if we move the channel state to a single context and share it between ChannelList, Channel and Thread we can remove this\n */\n const channelQueryResponse = await client.queryChannels(filters, sort, newOptions, {\n skipInitialization: enableOfflineSupport ? undefined : activeChannels.current,\n });\n if (isQueryStale() || !isMountedRef.current) {\n return;\n }\n\n const newChannels =\n queryType === 'loadChannels' && !staticChannelsActive && channels\n ? [...channels, ...channelQueryResponse]\n : channelQueryResponse.map((c) => {\n const existingChannel = client.activeChannels[c.cid];\n if (existingChannel) {\n return existingChannel;\n }\n\n return c;\n });\n\n setChannels(newChannels);\n setStaticChannelsActive(false);\n setHasNextPage(channelQueryResponse.length >= newOptions.limit);\n isQueryingRef.current = false;\n } catch (err: unknown) {\n isQueryingRef.current = false;\n await waitSeconds(2);\n\n if (isQueryStale()) {\n return;\n }\n\n // querying.current check is needed in order to make sure the next query call doesnt flick an error\n // state and then succeed (reconnect case)\n if (retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current) {\n setActiveQueryType(null);\n console.warn(err);\n\n setError(\n new Error(\n `Maximum number of retries reached in queryChannels. Last error message is: ${err}`,\n ),\n );\n return;\n }\n\n return queryChannels(queryType, retryCount + 1);\n }\n\n setActiveQueryType(null);\n };\n\n const refreshList = async () => {\n const now = Date.now();\n // Only allow pull-to-refresh 5 seconds after last successful refresh.\n if (now - lastRefresh.current < RETRY_INTERVAL_IN_MS && error === undefined) {\n return;\n }\n\n lastRefresh.current = Date.now();\n await queryChannels('refresh');\n };\n\n const reloadList = () => queryChannels('reload');\n\n /**\n * Equality check using stringified filters/sort ensure that we don't make un-necessary queryChannels api calls\n * for the scenario:\n *\n * <ChannelList\n * filters={{\n * members: { $in: ['vishal'] }\n * }}\n * ...\n * />\n *\n * Here we have passed filters as inline object, which means on every re-render of\n * parent component, ChannelList will receive new object reference (even though value is same), which\n * in return will trigger useEffect. To avoid this, we can add a value check.\n */\n const filterStr = useMemo(() => JSON.stringify(filters), [filters]);\n const sortStr = useMemo(() => JSON.stringify(sort), [sort]);\n\n useEffect(() => {\n const loadOfflineChannels = () => {\n if (!client?.user?.id) return;\n\n try {\n const channelsFromDB = getChannelsForFilterSort({\n currentUserId: client.user.id,\n filters,\n sort,\n });\n\n if (channelsFromDB) {\n const offlineChannels = client.hydrateActiveChannels(channelsFromDB, {\n offlineMode: true,\n skipInitialization: [], // passing empty array will clear out the existing messages from channel state, this removes the possibility of duplicate messages\n });\n\n setChannels(offlineChannels);\n setStaticChannelsActive(true);\n }\n } catch (e) {\n console.warn('Failed to get channels from database: ', e);\n }\n\n setActiveQueryType(null);\n };\n\n let listener: ReturnType<typeof DBSyncManager.onSyncStatusChange>;\n if (enableOfflineSupport) {\n // Any time DB is synced, we need to update the UI with local DB channels first,\n // and then call queryChannels to ensure any new channels are added to UI.\n listener = DBSyncManager.onSyncStatusChange((syncStatus) => {\n if (syncStatus) {\n loadOfflineChannels();\n reloadList();\n }\n });\n // On start, load the channels from local db.\n loadOfflineChannels();\n\n // If db is already synced (sync api and pending api calls), then\n // right away call queryChannels.\n const dbSyncStatus = DBSyncManager.getSyncStatus();\n if (dbSyncStatus) {\n reloadList();\n }\n } else {\n listener = client.on('connection.changed', async (event) => {\n if (event.online) {\n await refreshList();\n setForceUpdate((u) => u + 1);\n }\n });\n\n reloadList();\n }\n\n return () => listener?.unsubscribe?.();\n }, [filterStr, sortStr]);\n\n return {\n channels,\n error,\n hasNextPage,\n loadingChannels:\n activeQueryType === 'queryLocalDB'\n ? true\n : (activeQueryType === 'reload' || activeQueryType === null) && channels === null,\n loadingNextPage: activeQueryType === 'loadChannels',\n loadNextPage: queryChannels,\n refreshing: activeQueryType === 'refresh',\n refreshList,\n reloadList,\n // Although channels can be null, there is no practical case where channels will be null\n // when setChannels is used. setChannels is only recommended to be used for overriding\n // event handler. Thus instead of adding if check for channels === null, its better to\n // simply reassign types here.\n setChannels,\n staticChannelsActive,\n };\n};\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAIA,IAAAC,yBAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAEA,IAAAI,yBAAA,GAAAJ,OAAA;AAEA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,cAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AAEA,IAAMQ,WAAW,GAAG,SAAdA,WAAWA,CAAIC,OAAe;EAAA,OAClC,IAAIC,OAAO,CAAC,UAACC,OAAO,EAAK;IACvBC,UAAU,CAACD,OAAO,EAA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;IAEA,OAAO;MAAA,IAAA+B,SAAA;MAAA,QAAAA,SAAA,GAAMf,QAAQ,qBAARe,SAAA,CAAUC,WAAW,oBAArBD,SAAA,CAAUC,WAAW,EAAI;IAAA;EACxC,CAAC,EAAE,CAAC/B,SAAS,EAAEE,OAAO,CAAC,CAAC;EAExB,OAAO;IACLzF,QAAQ,EAARA,QAAQ;IACRK,KAAK,EAALA,KAAK;IACLY,WAAW,EAAXA,WAAW;IACXsG,eAAe,EACb1G,eAAe,KAAK,cAAc,GAC9B,IAAI,GACJ,CAACA,eAAe,KAAK,QAAQ,IAAIA,eAAe,KAAK,IAAI,KAAKb,QAAQ,KAAK,IAAI;IACrFwH,eAAe,EAAE3G,eAAe,KAAK,cAAc;IACnD4G,YAAY,EAAEvF,aAAa;IAC3BwF,UAAU,EAAE7G,eAAe,KAAK,SAAS;IACzCoE,WAAW,EAAXA,WAAW;IACXK,UAAU,EAAVA,UAAU;IAKVrF,WAAW,EAAXA,WAAW;IACXQ,oBAAoB,EAApBA;EACF,CAAC;AACH,CAAC;AAACkH,OAAA,CAAAzI,oBAAA,GAAAA,oBAAA"}
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "5.15.0-beta.4"
2
+ "version": "5.15.0-beta.6"
3
3
  }
@@ -15,8 +15,7 @@ var _useIsMountedRef = require("../../../hooks/useIsMountedRef");
15
15
  var _getChannelsForFilterSort = require("../../../store/apis/getChannelsForFilterSort");
16
16
  var _date = require("../../../utils/date");
17
17
  var _DBSyncManager = require("../../../utils/DBSyncManager");
18
- var _utils = require("../../../utils/utils");
19
- var _utils2 = require("../utils");
18
+ var _utils = require("../utils");
20
19
  var waitSeconds = function waitSeconds(seconds) {
21
20
  return new Promise(function (resolve) {
22
21
  setTimeout(resolve, seconds * _date.ONE_SECOND_IN_MS);
@@ -74,12 +73,7 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
74
73
  isQueryStale,
75
74
  currentRequestId,
76
75
  newOptions,
77
- failedMessagesInDb,
78
- cid,
79
- failedMessages,
80
76
  channelQueryResponse,
81
- _cid2,
82
- msgsToAdd,
83
77
  newChannels,
84
78
  _args = arguments;
85
79
  return _regenerator["default"].wrap(function _callee$(_context) {
@@ -115,35 +109,22 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
115
109
  currentRequestId = activeRequestId.current;
116
110
  setActiveQueryType(queryType);
117
111
  newOptions = (0, _extends2["default"])({
118
- limit: (_options$limit = options == null ? void 0 : options.limit) != null ? _options$limit : _utils2.MAX_QUERY_CHANNELS_LIMIT,
112
+ limit: (_options$limit = options == null ? void 0 : options.limit) != null ? _options$limit : _utils.MAX_QUERY_CHANNELS_LIMIT,
119
113
  offset: queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0
120
114
  }, options);
121
115
  _context.prev = 17;
122
- failedMessagesInDb = new Map();
123
- if (enableOfflineSupport) {
124
- for (cid in client.activeChannels) {
125
- failedMessages = getFailedMessages(client.activeChannels[cid]);
126
- if (failedMessages) failedMessagesInDb.set(cid, failedMessages);
127
- }
128
- }
129
- _context.next = 22;
116
+ _context.next = 20;
130
117
  return client.queryChannels(filters, sort, newOptions, {
131
- skipInitialization: activeChannels.current
118
+ skipInitialization: enableOfflineSupport ? undefined : activeChannels.current
132
119
  });
133
- case 22:
120
+ case 20:
134
121
  channelQueryResponse = _context.sent;
135
122
  if (!(isQueryStale() || !isMountedRef.current)) {
136
- _context.next = 25;
123
+ _context.next = 23;
137
124
  break;
138
125
  }
139
126
  return _context.abrupt("return");
140
- case 25:
141
- if (failedMessagesInDb.size) {
142
- for (_cid2 in client.activeChannels) {
143
- msgsToAdd = failedMessagesInDb.get(_cid2);
144
- if (msgsToAdd) client.activeChannels[_cid2].state.addMessagesSorted(msgsToAdd);
145
- }
146
- }
127
+ case 23:
147
128
  newChannels = queryType === 'loadChannels' && !staticChannelsActive && channels ? [].concat((0, _toConsumableArray2["default"])(channels), (0, _toConsumableArray2["default"])(channelQueryResponse)) : channelQueryResponse.map(function (c) {
148
129
  var existingChannel = client.activeChannels[c.cid];
149
130
  if (existingChannel) {
@@ -155,38 +136,38 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
155
136
  setStaticChannelsActive(false);
156
137
  setHasNextPage(channelQueryResponse.length >= newOptions.limit);
157
138
  isQueryingRef.current = false;
158
- _context.next = 46;
139
+ _context.next = 43;
159
140
  break;
160
- case 33:
161
- _context.prev = 33;
141
+ case 30:
142
+ _context.prev = 30;
162
143
  _context.t0 = _context["catch"](17);
163
144
  isQueryingRef.current = false;
164
- _context.next = 38;
145
+ _context.next = 35;
165
146
  return waitSeconds(2);
166
- case 38:
147
+ case 35:
167
148
  if (!isQueryStale()) {
168
- _context.next = 40;
149
+ _context.next = 37;
169
150
  break;
170
151
  }
171
152
  return _context.abrupt("return");
172
- case 40:
153
+ case 37:
173
154
  if (!(retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current)) {
174
- _context.next = 45;
155
+ _context.next = 42;
175
156
  break;
176
157
  }
177
158
  setActiveQueryType(null);
178
159
  console.warn(_context.t0);
179
160
  setError(new Error("Maximum number of retries reached in queryChannels. Last error message is: " + _context.t0));
180
161
  return _context.abrupt("return");
181
- case 45:
162
+ case 42:
182
163
  return _context.abrupt("return", queryChannels(queryType, retryCount + 1));
183
- case 46:
164
+ case 43:
184
165
  setActiveQueryType(null);
185
- case 47:
166
+ case 44:
186
167
  case "end":
187
168
  return _context.stop();
188
169
  }
189
- }, _callee, null, [[17, 33]]);
170
+ }, _callee, null, [[17, 30]]);
190
171
  }));
191
172
  return function queryChannels() {
192
173
  return _ref2.apply(this, arguments);
@@ -238,9 +219,11 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
238
219
  sort: sort
239
220
  });
240
221
  if (channelsFromDB) {
241
- setChannels(client.hydrateActiveChannels(channelsFromDB, {
242
- offlineMode: true
243
- }));
222
+ var offlineChannels = client.hydrateActiveChannels(channelsFromDB, {
223
+ offlineMode: true,
224
+ skipInitialization: []
225
+ });
226
+ setChannels(offlineChannels);
244
227
  setStaticChannelsActive(true);
245
228
  }
246
229
  } catch (e) {
@@ -309,19 +292,4 @@ var usePaginatedChannels = function usePaginatedChannels(_ref) {
309
292
  };
310
293
  };
311
294
  exports.usePaginatedChannels = usePaginatedChannels;
312
- function getFailedMessages(channel) {
313
- var failedMsgs = channel.state.messages.filter(function (m) {
314
- return m.status === _utils.MessageStatusTypes.FAILED;
315
- });
316
- if (failedMsgs.length) {
317
- return failedMsgs.map(function (m) {
318
- return (0, _extends2["default"])({}, m, {
319
- created_at: m.created_at.toISOString(),
320
- pinned_at: m.pinned_at ? m.pinned_at.toISOString() : null,
321
- updated_at: m.updated_at.toISOString()
322
- });
323
- });
324
- }
325
- return undefined;
326
- }
327
295
  //# sourceMappingURL=usePaginatedChannels.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_ActiveChannelsRefContext","_ChatContext","_useIsMountedRef","_getChannelsForFilterSort","_date","_DBSyncManager","_utils","_utils2","waitSeconds","seconds","Promise","resolve","setTimeout","ONE_SECOND_IN_MS","DEFAULT_OPTIONS","message_limit","MAX_NUMBER_OF_RETRIES","RETRY_INTERVAL_IN_MS","usePaginatedChannels","_ref","enableOfflineSupport","_ref$filters","filters","_ref$options","options","setForceUpdate","_ref$sort","sort","_useState","useState","_useState2","_slicedToArray2","channels","setChannels","_useState3","undefined","_useState4","error","setError","_useState5","_useState6","staticChannelsActive","setStaticChannelsActive","_useState7","_useState8","activeQueryType","setActiveQueryType","_useState9","_useState10","hasNextPage","setHasNextPage","activeChannels","useActiveChannelsRefContext","isMountedRef","useIsMountedRef","_useChatContext","useChatContext","client","filtersRef","useRef","sortRef","activeRequestId","isQueryingRef","lastRefresh","Date","now","queryChannels","_ref2","_asyncToGenerator2","_regenerator","mark","_callee","_options$limit","queryType","retryCount","hasUpdatedData","isQueryStale","currentRequestId","newOptions","failedMessagesInDb","cid","failedMessages","channelQueryResponse","_cid2","msgsToAdd","newChannels","_args","arguments","wrap","_callee$","_context","prev","next","length","current","abrupt","JSON","stringify","some","Boolean","_extends2","limit","MAX_QUERY_CHANNELS_LIMIT","offset","Map","getFailedMessages","set","skipInitialization","sent","size","get","state","addMessagesSorted","concat","_toConsumableArray2","map","c","existingChannel","t0","console","warn","Error","stop","apply","refreshList","_ref3","_callee2","_callee2$","_context2","reloadList","filterStr","useMemo","sortStr","useEffect","loadOfflineChannels","_client$user","user","id","channelsFromDB","getChannelsForFilterSort","currentUserId","hydrateActiveChannels","offlineMode","e","listener","DBSyncManager","onSyncStatusChange","syncStatus","dbSyncStatus","getSyncStatus","on","_ref4","_callee3","event","_callee3$","_context3","online","u","_x","_listener","unsubscribe","loadingChannels","loadingNextPage","loadNextPage","refreshing","exports","channel","failedMsgs","messages","filter","m","status","MessageStatusTypes","FAILED","created_at","toISOString","pinned_at","updated_at"],"sources":["usePaginatedChannels.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport type {\n Channel,\n ChannelFilters,\n ChannelOptions,\n ChannelSort,\n MessageResponse,\n} from 'stream-chat';\n\nimport { useActiveChannelsRefContext } from '../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext';\nimport { useChatContext } from '../../../contexts/chatContext/ChatContext';\nimport { useIsMountedRef } from '../../../hooks/useIsMountedRef';\n\nimport { getChannelsForFilterSort } from '../../../store/apis/getChannelsForFilterSort';\nimport type { DefaultStreamChatGenerics } from '../../../types/types';\nimport { ONE_SECOND_IN_MS } from '../../../utils/date';\nimport { DBSyncManager } from '../../../utils/DBSyncManager';\nimport { MessageStatusTypes } from '../../../utils/utils';\nimport { MAX_QUERY_CHANNELS_LIMIT } from '../utils';\n\nconst waitSeconds = (seconds: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, seconds * ONE_SECOND_IN_MS);\n });\n\ntype Parameters<StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics> =\n {\n enableOfflineSupport: boolean;\n filters: ChannelFilters<StreamChatGenerics>;\n options: ChannelOptions;\n setForceUpdate: React.Dispatch<React.SetStateAction<number>>;\n sort: ChannelSort<StreamChatGenerics>;\n };\n\nconst DEFAULT_OPTIONS = {\n message_limit: 10,\n};\n\nconst MAX_NUMBER_OF_RETRIES = 3;\nconst RETRY_INTERVAL_IN_MS = 5000;\n\ntype QueryType = 'queryLocalDB' | 'reload' | 'refresh' | 'loadChannels';\n\nexport type QueryChannels = (queryType?: QueryType, retryCount?: number) => Promise<void>;\n\nexport const usePaginatedChannels = <\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>({\n enableOfflineSupport,\n filters = {},\n options = DEFAULT_OPTIONS,\n setForceUpdate,\n sort = {},\n}: Parameters<StreamChatGenerics>) => {\n const [channels, setChannels] = useState<Channel<StreamChatGenerics>[] | null>(null);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [staticChannelsActive, setStaticChannelsActive] = useState<boolean>(false);\n const [activeQueryType, setActiveQueryType] = useState<QueryType | null>('queryLocalDB');\n const [hasNextPage, setHasNextPage] = useState<boolean>(false);\n const activeChannels = useActiveChannelsRefContext();\n const isMountedRef = useIsMountedRef();\n const { client } = useChatContext<StreamChatGenerics>();\n\n const filtersRef = useRef<typeof filters | null>(null);\n const sortRef = useRef<typeof sort | null>(null);\n const activeRequestId = useRef<number>(0);\n const isQueryingRef = useRef(false);\n const lastRefresh = useRef(Date.now());\n\n const queryChannels: QueryChannels = async (\n queryType: QueryType = 'loadChannels',\n retryCount = 0,\n ): Promise<void> => {\n if (!client || !isMountedRef.current) return;\n\n const hasUpdatedData =\n queryType === 'loadChannels' ||\n queryType === 'refresh' ||\n [\n JSON.stringify(filtersRef.current) !== JSON.stringify(filters),\n JSON.stringify(sortRef.current) !== JSON.stringify(sort),\n ].some(Boolean);\n\n const isQueryStale = () => !isMountedRef || activeRequestId.current !== currentRequestId;\n\n /**\n * We don't need to make another call to query channels if we don't\n * have new data for the query to include\n * */\n if (!hasUpdatedData) {\n if (activeQueryType === null) return;\n }\n\n filtersRef.current = filters;\n sortRef.current = sort;\n isQueryingRef.current = true;\n setError(undefined);\n activeRequestId.current++;\n const currentRequestId = activeRequestId.current;\n setActiveQueryType(queryType);\n\n const newOptions = {\n limit: options?.limit ?? MAX_QUERY_CHANNELS_LIMIT,\n offset:\n queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0,\n ...options,\n };\n\n try {\n // If failed messages were present in DB it would be in the channel state now and be overwritten by the queryChannels call\n // So we store them in a separate object and add them back to the channel state after the queryChannels call\n const failedMessagesInDb: Map<string, MessageResponse<StreamChatGenerics>[]> = new Map();\n if (enableOfflineSupport) {\n for (const cid in client.activeChannels) {\n const failedMessages = getFailedMessages(client.activeChannels[cid]);\n if (failedMessages) failedMessagesInDb.set(cid, failedMessages);\n }\n }\n\n /**\n * We skipInitialization here for handling race condition between ChannelList, Channel (and Thread)\n * when they all (may) update the channel state at the same time (when connection state recovers)\n * TODO: if we move the channel state to a single context and share it between ChannelList, Channel and Thread we can remove this\n */\n const channelQueryResponse = await client.queryChannels(filters, sort, newOptions, {\n skipInitialization: activeChannels.current,\n });\n if (isQueryStale() || !isMountedRef.current) {\n return;\n }\n\n if (failedMessagesInDb.size) {\n for (const cid in client.activeChannels) {\n const msgsToAdd = failedMessagesInDb.get(cid);\n if (msgsToAdd) client.activeChannels[cid].state.addMessagesSorted(msgsToAdd);\n }\n }\n\n const newChannels =\n queryType === 'loadChannels' && !staticChannelsActive && channels\n ? [...channels, ...channelQueryResponse]\n : channelQueryResponse.map((c) => {\n const existingChannel = client.activeChannels[c.cid];\n if (existingChannel) {\n return existingChannel;\n }\n\n return c;\n });\n\n setChannels(newChannels);\n setStaticChannelsActive(false);\n setHasNextPage(channelQueryResponse.length >= newOptions.limit);\n isQueryingRef.current = false;\n } catch (err: unknown) {\n isQueryingRef.current = false;\n await waitSeconds(2);\n\n if (isQueryStale()) {\n return;\n }\n\n // querying.current check is needed in order to make sure the next query call doesnt flick an error\n // state and then succeed (reconnect case)\n if (retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current) {\n setActiveQueryType(null);\n console.warn(err);\n\n setError(\n new Error(\n `Maximum number of retries reached in queryChannels. Last error message is: ${err}`,\n ),\n );\n return;\n }\n\n return queryChannels(queryType, retryCount + 1);\n }\n\n setActiveQueryType(null);\n };\n\n const refreshList = async () => {\n const now = Date.now();\n // Only allow pull-to-refresh 5 seconds after last successful refresh.\n if (now - lastRefresh.current < RETRY_INTERVAL_IN_MS && error === undefined) {\n return;\n }\n\n lastRefresh.current = Date.now();\n await queryChannels('refresh');\n };\n\n const reloadList = () => queryChannels('reload');\n\n /**\n * Equality check using stringified filters/sort ensure that we don't make un-necessary queryChannels api calls\n * for the scenario:\n *\n * <ChannelList\n * filters={{\n * members: { $in: ['vishal'] }\n * }}\n * ...\n * />\n *\n * Here we have passed filters as inline object, which means on every re-render of\n * parent component, ChannelList will receive new object reference (even though value is same), which\n * in return will trigger useEffect. To avoid this, we can add a value check.\n */\n const filterStr = useMemo(() => JSON.stringify(filters), [filters]);\n const sortStr = useMemo(() => JSON.stringify(sort), [sort]);\n\n useEffect(() => {\n const loadOfflineChannels = () => {\n if (!client?.user?.id) return;\n\n try {\n const channelsFromDB = getChannelsForFilterSort({\n currentUserId: client.user.id,\n filters,\n sort,\n });\n\n if (channelsFromDB) {\n setChannels(\n client.hydrateActiveChannels(channelsFromDB, {\n offlineMode: true,\n }),\n );\n setStaticChannelsActive(true);\n }\n } catch (e) {\n console.warn('Failed to get channels from database: ', e);\n }\n\n setActiveQueryType(null);\n };\n\n let listener: ReturnType<typeof DBSyncManager.onSyncStatusChange>;\n if (enableOfflineSupport) {\n // Any time DB is synced, we need to update the UI with local DB channels first,\n // and then call queryChannels to ensure any new channels are added to UI.\n listener = DBSyncManager.onSyncStatusChange((syncStatus) => {\n if (syncStatus) {\n loadOfflineChannels();\n reloadList();\n }\n });\n // On start, load the channels from local db.\n loadOfflineChannels();\n\n // If db is already synced (sync api and pending api calls), then\n // right away call queryChannels.\n const dbSyncStatus = DBSyncManager.getSyncStatus();\n if (dbSyncStatus) {\n reloadList();\n }\n } else {\n listener = client.on('connection.changed', async (event) => {\n if (event.online) {\n await refreshList();\n setForceUpdate((u) => u + 1);\n }\n });\n\n reloadList();\n }\n\n return () => listener?.unsubscribe?.();\n }, [filterStr, sortStr]);\n\n return {\n channels,\n error,\n hasNextPage,\n loadingChannels:\n activeQueryType === 'queryLocalDB'\n ? true\n : (activeQueryType === 'reload' || activeQueryType === null) && channels === null,\n loadingNextPage: activeQueryType === 'loadChannels',\n loadNextPage: queryChannels,\n refreshing: activeQueryType === 'refresh',\n refreshList,\n reloadList,\n // Although channels can be null, there is no practical case where channels will be null\n // when setChannels is used. setChannels is only recommended to be used for overriding\n // event handler. Thus instead of adding if check for channels === null, its better to\n // simply reassign types here.\n setChannels,\n staticChannelsActive,\n };\n};\n\nfunction getFailedMessages<\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>(channel: Channel<StreamChatGenerics>): MessageResponse<StreamChatGenerics>[] | undefined {\n const failedMsgs = channel.state.messages.filter((m) => m.status === MessageStatusTypes.FAILED);\n if (failedMsgs.length) {\n return failedMsgs.map(\n (m) =>\n ({\n ...m,\n created_at: m.created_at.toISOString(),\n pinned_at: m.pinned_at ? m.pinned_at.toISOString() : null,\n updated_at: m.updated_at.toISOString(),\n } as MessageResponse<StreamChatGenerics>),\n );\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,yBAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAEA,IAAAI,yBAAA,GAAAJ,OAAA;AAEA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,cAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AACA,IAAAQ,OAAA,GAAAR,OAAA;AAEA,IAAMS,WAAW,GAAG,SAAdA,WAAWA,CAAIC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KVhG,WAAW,EAAXA,WAAW;IACXQ,oBAAoB,EAApBA;EACF,CAAC;AACH,CAAC;AAAC4H,OAAA,CAAAnJ,oBAAA,GAAAA,oBAAA;AAEF,SAASuF,iBAAiBA,CAExB6D,OAAoC,EAAqD;EACzF,IAAMC,UAAU,GAAGD,OAAO,CAACvD,KAAK,CAACyD,QAAQ,CAACC,MAAM,CAAC,UAACC,CAAC;IAAA,OAAKA,CAAC,CAACC,MAAM,KAAKC,yBAAkB,CAACC,MAAM;EAAA,EAAC;EAC/F,IAAIN,UAAU,CAAC1E,MAAM,EAAE;IACrB,OAAO0E,UAAU,CAACpD,GAAG,CACnB,UAACuD,CAAC;MAAA,WAAAtE,SAAA,iBAEKsE,CAAC;QACJI,UAAU,EAAEJ,CAAC,CAACI,UAAU,CAACC,WAAW,EAAE;QACtCC,SAAS,EAAEN,CAAC,CAACM,SAAS,GAAGN,CAAC,CAACM,SAAS,CAACD,WAAW,EAAE,GAAG,IAAI;QACzDE,UAAU,EAAEP,CAAC,CAACO,UAAU,CAACF,WAAW;MAAE;IAAA,CACC,CAC5C;EACH;EACA,OAAO5I,SAAS;AAClB"}
1
+ {"version":3,"names":["_react","require","_ActiveChannelsRefContext","_ChatContext","_useIsMountedRef","_getChannelsForFilterSort","_date","_DBSyncManager","_utils","waitSeconds","seconds","Promise","resolve","setTimeout","ONE_SECOND_IN_MS","DEFAULT_OPTIONS","message_limit","MAX_NUMBER_OF_RETRIES","RETRY_INTERVAL_IN_MS","usePaginatedChannels","_ref","enableOfflineSupport","_ref$filters","filters","_ref$options","options","setForceUpdate","_ref$sort","sort","_useState","useState","_useState2","_slicedToArray2","channels","setChannels","_useState3","undefined","_useState4","error","setError","_useState5","_useState6","staticChannelsActive","setStaticChannelsActive","_useState7","_useState8","activeQueryType","setActiveQueryType","_useState9","_useState10","hasNextPage","setHasNextPage","activeChannels","useActiveChannelsRefContext","isMountedRef","useIsMountedRef","_useChatContext","useChatContext","client","filtersRef","useRef","sortRef","activeRequestId","isQueryingRef","lastRefresh","Date","now","queryChannels","_ref2","_asyncToGenerator2","_regenerator","mark","_callee","_options$limit","queryType","retryCount","hasUpdatedData","isQueryStale","currentRequestId","newOptions","channelQueryResponse","newChannels","_args","arguments","wrap","_callee$","_context","prev","next","length","current","abrupt","JSON","stringify","some","Boolean","_extends2","limit","MAX_QUERY_CHANNELS_LIMIT","offset","skipInitialization","sent","concat","_toConsumableArray2","map","c","existingChannel","cid","t0","console","warn","Error","stop","apply","refreshList","_ref3","_callee2","_callee2$","_context2","reloadList","filterStr","useMemo","sortStr","useEffect","loadOfflineChannels","_client$user","user","id","channelsFromDB","getChannelsForFilterSort","currentUserId","offlineChannels","hydrateActiveChannels","offlineMode","e","listener","DBSyncManager","onSyncStatusChange","syncStatus","dbSyncStatus","getSyncStatus","on","_ref4","_callee3","event","_callee3$","_context3","online","u","_x","_listener","unsubscribe","loadingChannels","loadingNextPage","loadNextPage","refreshing","exports"],"sources":["usePaginatedChannels.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport type { Channel, ChannelFilters, ChannelOptions, ChannelSort } from 'stream-chat';\n\nimport { useActiveChannelsRefContext } from '../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext';\nimport { useChatContext } from '../../../contexts/chatContext/ChatContext';\nimport { useIsMountedRef } from '../../../hooks/useIsMountedRef';\n\nimport { getChannelsForFilterSort } from '../../../store/apis/getChannelsForFilterSort';\nimport type { DefaultStreamChatGenerics } from '../../../types/types';\nimport { ONE_SECOND_IN_MS } from '../../../utils/date';\nimport { DBSyncManager } from '../../../utils/DBSyncManager';\nimport { MAX_QUERY_CHANNELS_LIMIT } from '../utils';\n\nconst waitSeconds = (seconds: number) =>\n new Promise((resolve) => {\n setTimeout(resolve, seconds * ONE_SECOND_IN_MS);\n });\n\ntype Parameters<StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics> =\n {\n enableOfflineSupport: boolean;\n filters: ChannelFilters<StreamChatGenerics>;\n options: ChannelOptions;\n setForceUpdate: React.Dispatch<React.SetStateAction<number>>;\n sort: ChannelSort<StreamChatGenerics>;\n };\n\nconst DEFAULT_OPTIONS = {\n message_limit: 10,\n};\n\nconst MAX_NUMBER_OF_RETRIES = 3;\nconst RETRY_INTERVAL_IN_MS = 5000;\n\ntype QueryType = 'queryLocalDB' | 'reload' | 'refresh' | 'loadChannels';\n\nexport type QueryChannels = (queryType?: QueryType, retryCount?: number) => Promise<void>;\n\nexport const usePaginatedChannels = <\n StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,\n>({\n enableOfflineSupport,\n filters = {},\n options = DEFAULT_OPTIONS,\n setForceUpdate,\n sort = {},\n}: Parameters<StreamChatGenerics>) => {\n const [channels, setChannels] = useState<Channel<StreamChatGenerics>[] | null>(null);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [staticChannelsActive, setStaticChannelsActive] = useState<boolean>(false);\n const [activeQueryType, setActiveQueryType] = useState<QueryType | null>('queryLocalDB');\n const [hasNextPage, setHasNextPage] = useState<boolean>(false);\n const activeChannels = useActiveChannelsRefContext();\n const isMountedRef = useIsMountedRef();\n const { client } = useChatContext<StreamChatGenerics>();\n\n const filtersRef = useRef<typeof filters | null>(null);\n const sortRef = useRef<typeof sort | null>(null);\n const activeRequestId = useRef<number>(0);\n const isQueryingRef = useRef(false);\n const lastRefresh = useRef(Date.now());\n\n const queryChannels: QueryChannels = async (\n queryType: QueryType = 'loadChannels',\n retryCount = 0,\n ): Promise<void> => {\n if (!client || !isMountedRef.current) return;\n\n const hasUpdatedData =\n queryType === 'loadChannels' ||\n queryType === 'refresh' ||\n [\n JSON.stringify(filtersRef.current) !== JSON.stringify(filters),\n JSON.stringify(sortRef.current) !== JSON.stringify(sort),\n ].some(Boolean);\n\n const isQueryStale = () => !isMountedRef || activeRequestId.current !== currentRequestId;\n\n /**\n * We don't need to make another call to query channels if we don't\n * have new data for the query to include\n * */\n if (!hasUpdatedData) {\n if (activeQueryType === null) return;\n }\n\n filtersRef.current = filters;\n sortRef.current = sort;\n isQueryingRef.current = true;\n setError(undefined);\n activeRequestId.current++;\n const currentRequestId = activeRequestId.current;\n setActiveQueryType(queryType);\n\n const newOptions = {\n limit: options?.limit ?? MAX_QUERY_CHANNELS_LIMIT,\n offset:\n queryType === 'loadChannels' && !staticChannelsActive && channels ? channels.length : 0,\n ...options,\n };\n\n try {\n /**\n * We skipInitialization here for handling race condition between ChannelList, Channel (and Thread)\n * when they all (may) update the channel state at the same time (when connection state recovers)\n * TODO: if we move the channel state to a single context and share it between ChannelList, Channel and Thread we can remove this\n */\n const channelQueryResponse = await client.queryChannels(filters, sort, newOptions, {\n skipInitialization: enableOfflineSupport ? undefined : activeChannels.current,\n });\n if (isQueryStale() || !isMountedRef.current) {\n return;\n }\n\n const newChannels =\n queryType === 'loadChannels' && !staticChannelsActive && channels\n ? [...channels, ...channelQueryResponse]\n : channelQueryResponse.map((c) => {\n const existingChannel = client.activeChannels[c.cid];\n if (existingChannel) {\n return existingChannel;\n }\n\n return c;\n });\n\n setChannels(newChannels);\n setStaticChannelsActive(false);\n setHasNextPage(channelQueryResponse.length >= newOptions.limit);\n isQueryingRef.current = false;\n } catch (err: unknown) {\n isQueryingRef.current = false;\n await waitSeconds(2);\n\n if (isQueryStale()) {\n return;\n }\n\n // querying.current check is needed in order to make sure the next query call doesnt flick an error\n // state and then succeed (reconnect case)\n if (retryCount === MAX_NUMBER_OF_RETRIES && !isQueryingRef.current) {\n setActiveQueryType(null);\n console.warn(err);\n\n setError(\n new Error(\n `Maximum number of retries reached in queryChannels. Last error message is: ${err}`,\n ),\n );\n return;\n }\n\n return queryChannels(queryType, retryCount + 1);\n }\n\n setActiveQueryType(null);\n };\n\n const refreshList = async () => {\n const now = Date.now();\n // Only allow pull-to-refresh 5 seconds after last successful refresh.\n if (now - lastRefresh.current < RETRY_INTERVAL_IN_MS && error === undefined) {\n return;\n }\n\n lastRefresh.current = Date.now();\n await queryChannels('refresh');\n };\n\n const reloadList = () => queryChannels('reload');\n\n /**\n * Equality check using stringified filters/sort ensure that we don't make un-necessary queryChannels api calls\n * for the scenario:\n *\n * <ChannelList\n * filters={{\n * members: { $in: ['vishal'] }\n * }}\n * ...\n * />\n *\n * Here we have passed filters as inline object, which means on every re-render of\n * parent component, ChannelList will receive new object reference (even though value is same), which\n * in return will trigger useEffect. To avoid this, we can add a value check.\n */\n const filterStr = useMemo(() => JSON.stringify(filters), [filters]);\n const sortStr = useMemo(() => JSON.stringify(sort), [sort]);\n\n useEffect(() => {\n const loadOfflineChannels = () => {\n if (!client?.user?.id) return;\n\n try {\n const channelsFromDB = getChannelsForFilterSort({\n currentUserId: client.user.id,\n filters,\n sort,\n });\n\n if (channelsFromDB) {\n const offlineChannels = client.hydrateActiveChannels(channelsFromDB, {\n offlineMode: true,\n skipInitialization: [], // passing empty array will clear out the existing messages from channel state, this removes the possibility of duplicate messages\n });\n\n setChannels(offlineChannels);\n setStaticChannelsActive(true);\n }\n } catch (e) {\n console.warn('Failed to get channels from database: ', e);\n }\n\n setActiveQueryType(null);\n };\n\n let listener: ReturnType<typeof DBSyncManager.onSyncStatusChange>;\n if (enableOfflineSupport) {\n // Any time DB is synced, we need to update the UI with local DB channels first,\n // and then call queryChannels to ensure any new channels are added to UI.\n listener = DBSyncManager.onSyncStatusChange((syncStatus) => {\n if (syncStatus) {\n loadOfflineChannels();\n reloadList();\n }\n });\n // On start, load the channels from local db.\n loadOfflineChannels();\n\n // If db is already synced (sync api and pending api calls), then\n // right away call queryChannels.\n const dbSyncStatus = DBSyncManager.getSyncStatus();\n if (dbSyncStatus) {\n reloadList();\n }\n } else {\n listener = client.on('connection.changed', async (event) => {\n if (event.online) {\n await refreshList();\n setForceUpdate((u) => u + 1);\n }\n });\n\n reloadList();\n }\n\n return () => listener?.unsubscribe?.();\n }, [filterStr, sortStr]);\n\n return {\n channels,\n error,\n hasNextPage,\n loadingChannels:\n activeQueryType === 'queryLocalDB'\n ? true\n : (activeQueryType === 'reload' || activeQueryType === null) && channels === null,\n loadingNextPage: activeQueryType === 'loadChannels',\n loadNextPage: queryChannels,\n refreshing: activeQueryType === 'refresh',\n refreshList,\n reloadList,\n // Although channels can be null, there is no practical case where channels will be null\n // when setChannels is used. setChannels is only recommended to be used for overriding\n // event handler. Thus instead of adding if check for channels === null, its better to\n // simply reassign types here.\n setChannels,\n staticChannelsActive,\n };\n};\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAIA,IAAAC,yBAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAEA,IAAAI,yBAAA,GAAAJ,OAAA;AAEA,IAAAK,KAAA,GAAAL,OAAA;AACA,IAAAM,cAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AAEA,IAAMQ,WAAW,GAAG,SAAdA,WAAWA,CAAIC,OAAe;EAAA,OAClC,IAAIC,OAAO,CAAC,UAACC,OAAO,EAAK;IACvBC,UAAU,CAACD,OAAO,EAAEF,OAAO,GAAGI,sBAAgB,CAAC;EACjD,CAAC,CAAC;AAAA;AAWJ,IAAMC,eAAe,GAAG;EACtBC,aAAa,EAAE;AACjB,CAAC;AAED,IAAMC,qBAAqB,GAAG,CAAC;AAC/B,IAAMC,oBAAoB,GAAG,IAAI;AAM1B,IAAMC,oBAAoB,GAAG,SAAvBA,oBAAoBA,CAAAC,IAAA,EAQK;EAAA,IALpCC,oBAAoB,GAAAD,IAAA,CAApBC,oBAAoB;IAAAC,YAAA,GAAAF,IAAA,CACpBG,OAAO;IAAPA,OAAO,GAAAD,YAAA,cAAG,CAAC,CAAC,GAAAA,YAAA;IAAAE,YAAA,GAAAJ,IAAA,CACZK,OAAO;IAAPA,OAAO,GAAAD,YAAA,cAAGT,eAAe,GAAAS,YAAA;IACzBE,cAAc,GAAAN,IAAA,CAAdM,cAAc;IAAAC,SAAA,GAAAP,IAAA,CACdQ,IAAI;IAAJA,IAA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U;IAKVrF,WAAW,EAAXA,WAAW;IACXQ,oBAAoB,EAApBA;EACF,CAAC;AACH,CAAC;AAACkH,OAAA,CAAAzI,oBAAA,GAAAA,oBAAA"}
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "5.15.0-beta.4"
2
+ "version": "5.15.0-beta.6"
3
3
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "stream-chat-react-native-core",
3
3
  "description": "The official React Native and Expo components for Stream Chat, a service for building chat applications",
4
- "version": "5.15.0-beta.4",
4
+ "version": "5.15.0-beta.6",
5
5
  "author": {
6
6
  "company": "Stream.io Inc",
7
7
  "name": "Stream.io Inc"
@@ -1,12 +1,6 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react';
2
2
 
3
- import type {
4
- Channel,
5
- ChannelFilters,
6
- ChannelOptions,
7
- ChannelSort,
8
- MessageResponse,
9
- } from 'stream-chat';
3
+ import type { Channel, ChannelFilters, ChannelOptions, ChannelSort } from 'stream-chat';
10
4
 
11
5
  import { useActiveChannelsRefContext } from '../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext';
12
6
  import { useChatContext } from '../../../contexts/chatContext/ChatContext';
@@ -16,7 +10,6 @@ import { getChannelsForFilterSort } from '../../../store/apis/getChannelsForFilt
16
10
  import type { DefaultStreamChatGenerics } from '../../../types/types';
17
11
  import { ONE_SECOND_IN_MS } from '../../../utils/date';
18
12
  import { DBSyncManager } from '../../../utils/DBSyncManager';
19
- import { MessageStatusTypes } from '../../../utils/utils';
20
13
  import { MAX_QUERY_CHANNELS_LIMIT } from '../utils';
21
14
 
22
15
  const waitSeconds = (seconds: number) =>
@@ -108,35 +101,18 @@ export const usePaginatedChannels = <
108
101
  };
109
102
 
110
103
  try {
111
- // If failed messages were present in DB it would be in the channel state now and be overwritten by the queryChannels call
112
- // So we store them in a separate object and add them back to the channel state after the queryChannels call
113
- const failedMessagesInDb: Map<string, MessageResponse<StreamChatGenerics>[]> = new Map();
114
- if (enableOfflineSupport) {
115
- for (const cid in client.activeChannels) {
116
- const failedMessages = getFailedMessages(client.activeChannels[cid]);
117
- if (failedMessages) failedMessagesInDb.set(cid, failedMessages);
118
- }
119
- }
120
-
121
104
  /**
122
105
  * We skipInitialization here for handling race condition between ChannelList, Channel (and Thread)
123
106
  * when they all (may) update the channel state at the same time (when connection state recovers)
124
107
  * TODO: if we move the channel state to a single context and share it between ChannelList, Channel and Thread we can remove this
125
108
  */
126
109
  const channelQueryResponse = await client.queryChannels(filters, sort, newOptions, {
127
- skipInitialization: activeChannels.current,
110
+ skipInitialization: enableOfflineSupport ? undefined : activeChannels.current,
128
111
  });
129
112
  if (isQueryStale() || !isMountedRef.current) {
130
113
  return;
131
114
  }
132
115
 
133
- if (failedMessagesInDb.size) {
134
- for (const cid in client.activeChannels) {
135
- const msgsToAdd = failedMessagesInDb.get(cid);
136
- if (msgsToAdd) client.activeChannels[cid].state.addMessagesSorted(msgsToAdd);
137
- }
138
- }
139
-
140
116
  const newChannels =
141
117
  queryType === 'loadChannels' && !staticChannelsActive && channels
142
118
  ? [...channels, ...channelQueryResponse]
@@ -224,11 +200,12 @@ export const usePaginatedChannels = <
224
200
  });
225
201
 
226
202
  if (channelsFromDB) {
227
- setChannels(
228
- client.hydrateActiveChannels(channelsFromDB, {
229
- offlineMode: true,
230
- }),
231
- );
203
+ const offlineChannels = client.hydrateActiveChannels(channelsFromDB, {
204
+ offlineMode: true,
205
+ skipInitialization: [], // passing empty array will clear out the existing messages from channel state, this removes the possibility of duplicate messages
206
+ });
207
+
208
+ setChannels(offlineChannels);
232
209
  setStaticChannelsActive(true);
233
210
  }
234
211
  } catch (e) {
@@ -292,21 +269,3 @@ export const usePaginatedChannels = <
292
269
  staticChannelsActive,
293
270
  };
294
271
  };
295
-
296
- function getFailedMessages<
297
- StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
298
- >(channel: Channel<StreamChatGenerics>): MessageResponse<StreamChatGenerics>[] | undefined {
299
- const failedMsgs = channel.state.messages.filter((m) => m.status === MessageStatusTypes.FAILED);
300
- if (failedMsgs.length) {
301
- return failedMsgs.map(
302
- (m) =>
303
- ({
304
- ...m,
305
- created_at: m.created_at.toISOString(),
306
- pinned_at: m.pinned_at ? m.pinned_at.toISOString() : null,
307
- updated_at: m.updated_at.toISOString(),
308
- } as MessageResponse<StreamChatGenerics>),
309
- );
310
- }
311
- return undefined;
312
- }
package/src/version.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "5.15.0-beta.4"
2
+ "version": "5.15.0-beta.6"
3
3
  }