Skip to content

Instantly share code, notes, and snippets.

@vishalnarkhede
Created March 31, 2021 11:22
Show Gist options
  • Save vishalnarkhede/11e8d659bc1194fe258d65d8ef94545e to your computer and use it in GitHub Desktop.
Save vishalnarkhede/11e8d659bc1194fe258d65d8ef94545e to your computer and use it in GitHub Desktop.
Custom hook to update user references in message objects in all activeChannels.
import {useEffect} from 'react';
/**
* Custom hook to update user references in message objects in all activeChannels.
*
* @param {*} chatClient
*/
export const useUserUpdatedListener = (chatClient) => {
useEffect(() => {
const updateUserReferences = (e) => {
if (e.user.id !== chatClient.userID) return;
const activeChannels = chatClient.activeChannels;
for (const channelID in activeChannels) {
const channel = activeChannels[channelID];
const state = channel.state;
// search the messages and update as needed...
if (state) {
state.messages.forEach(m => {
if (m.user.id !== e.user.id) { return }
m.user = e.user;
})
// Fire this event on channel, so internally Channel component will update the UI state.
channel._callChannelListeners({
type: 'user.updated'
})
}
}
}
chatClient.on('user.updated', updateUserReferences);
return () => {
chatClient.off('user.updated', updateUserReferences);
}
}, [chatClient])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment