Skip to content

Commit

Permalink
fix: call missing useEffect, use immutable data for chat
Browse files Browse the repository at this point in the history
  • Loading branch information
codeofmochi committed Aug 4, 2021
1 parent e836e7c commit ef4e533
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 25 deletions.
3 changes: 2 additions & 1 deletion src/hooks/chat.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { fromJS } from 'immutable';
import { useQuery } from 'react-query';
import * as Api from '../api';
import { buildItemChatKey } from '../config/keys';
Expand All @@ -16,7 +17,7 @@ export default (queryConfig: QueryClientConfig) => {
useQuery({
queryKey: buildItemChatKey(itemId),
queryFn: () =>
Api.getItemChat(itemId, queryConfig).then((data) => data),
Api.getItemChat(itemId, queryConfig).then((data) => fromJS(data)),
...defaultOptions,
enabled: Boolean(itemId),
}),
Expand Down
54 changes: 30 additions & 24 deletions src/ws/hooks/chat.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Record } from 'immutable';
import { useEffect } from 'react';
import { QueryClient } from 'react-query';
import { buildItemChatKey } from '../../config/keys';
import { Chat, ChatMessage, UUID } from '../../types';
Expand All @@ -16,39 +18,43 @@ export default (
) => ({
/**
* React hook to subscribe to the updates of the given chat ID
* @param chatId The ID of the chat of which to observves updates
* @param chatId The ID of the chat of which to observe updates
*/
useItemChatUpdates: (chatId: UUID) => {
if (!chatId) {
return;
}
useEffect(() => {
if (!chatId) {
return;
}

const channel: Channel = { name: chatId, topic: 'chat/item' };
const channel: Channel = { name: chatId, topic: 'chat/item' };

const handler = (event: ChatEvent) => {
if (event.kind === 'item') {
const chatKey = buildItemChatKey(chatId);
const current: Chat | undefined = queryClient.getQueryData(chatKey);
const handler = (event: ChatEvent) => {
if (event.kind === 'item') {
const chatKey = buildItemChatKey(chatId);
const current: Record<Chat> | undefined = queryClient.getQueryData(
chatKey,
);

if (current) {
switch (event.op) {
case 'publish': {
const msg = event.message;
const newChat = Object.assign({}, current);
newChat.messages = [...current.messages];
newChat.messages.push(msg);
queryClient.setQueryData(chatKey, newChat);
break;
if (current) {
switch (event.op) {
case 'publish': {
const mutation = current.update('messages', (messages) => [
...messages,
event.message,
]);
queryClient.setQueryData(chatKey, mutation);
break;
}
}
}
}
}
};
};

websocketClient.subscribe(channel, handler);
websocketClient.subscribe(channel, handler);

return function cleanup() {
websocketClient.unsubscribe(channel, handler);
};
return function cleanup() {
websocketClient.unsubscribe(channel, handler);
};
}, [chatId]);
},
});

0 comments on commit ef4e533

Please sign in to comment.