Created
March 31, 2021 11:22
-
-
Save vishalnarkhede/11e8d659bc1194fe258d65d8ef94545e to your computer and use it in GitHub Desktop.
Custom hook to update user references in message objects in all activeChannels.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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