You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When you send a message using `send()`, the server echoes it back to all subscribers in the room, including the sender. If your application adds the message to the UI immediately after calling `send()` and also appends it when received via `subscribe()`, the message will appear twice.
235
+
236
+
To avoid this, use one of the following approaches:
237
+
238
+
**Approach 1: Only render messages from the subscription.** Do not add the message to the UI when calling `send()`. Instead, rely solely on the subscription listener to display all messages, including your own. This is the simplest approach and ensures consistency with the server's message ordering and `serial` assignment.
239
+
240
+
**Approach 2: Use `serial` to deduplicate.** If you want optimistic UI updates (displaying the message immediately on send for a more responsive experience), use the `serial` property of the message returned by `send()` to filter out the duplicate when it arrives via the subscription. When a new message event is received, check whether a message with the same `serial` already exists in your local list before adding it.
241
+
</Aside>
242
+
243
+
The following example demonstrates approach 2, using `serial`-based deduplication to prevent duplicate messages:
244
+
245
+
<Code>
246
+
```javascript
247
+
import { ChatMessageEventType } from'@ably/chat';
248
+
constmessages= [];
249
+
250
+
// Subscribe to incoming messages
251
+
room.messages.subscribe((event) => {
252
+
if (event.type===ChatMessageEventType.Created) {
253
+
// Only add the message if it doesn't already exist in the list
0 commit comments