Created
March 12, 2024 12:23
-
-
Save vishalnarkhede/8e668fac55b7359aab90cc7060c42e31 to your computer and use it in GitHub Desktop.
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
// Use threads state in your app to show a list of threads. | |
// Each thread should have a list of replies. | |
// Parent message can be rendered using `thread.message` and replies can be rendered using `thread.latest_replies`. | |
const [threads, setThreads] = useState([]); | |
useEffect(() => { | |
client.queryThreads() | |
.then((threads) => { | |
setThreads(threads); | |
}); | |
}, []); | |
useEffect(() => { | |
const handleEvent = (event) => { | |
const message = event.message; | |
// If the message is not a reply, then don't do anything. | |
if (!message?.parent_id) return; | |
// Find the parent message in threads loaded on UI. | |
const parentInThreadsIdx = threads.findIndex((thread) => thread.id === message.parent_id); | |
// If the parent message is not in threads, then don't do anything. | |
// Slack doesn't append a new thread dynamically to the list, only shows a notification dot. | |
// But one can use `client.getThread()` to fetch the new thread. | |
if (parentInThreadsIdx === -1) { | |
return; | |
} | |
setThreads((threads) => { | |
const newThreads = [...threads]; | |
// add the new reply to the latest_replies state of the parent message. | |
newThreads[parentInThreadsIdx].addReply(message); | |
return newThreads; | |
}); | |
}; | |
const unsubscribe = client.on('notification.thread_message_new', handleEvent).unsubscribe; | |
return unsubscribe; | |
}, [threads, setThreads]) | |
const threadIds = threads.map((thread) => thread.id).join(','); | |
useEffect(() => { | |
const handleEvent = (event) => { | |
const message = event.message; | |
if (!message) return; | |
if (message.parent_id) { | |
// check if one of the thread replies was deleted or updated | |
const thread = threads.find((thread) => thread.message.id === message.parent_id); | |
if (!thread) return; | |
thread.updateReply(message); | |
} else { | |
// check if one of the thread parent messages was deleted or updated | |
const thread = threads.find((thread) => thread.message.id === message.id); | |
if (!thread) return; | |
thread.message = formatMessage(message); | |
} | |
setThreads([...threads]); | |
}; | |
const { unsubscribe: u1 } = client.on('message.updated', handleEvent); | |
const { unsubscribe: u2 } = client.on('message.deleted', handleEvent); | |
const { unsubscribe: u3 } = client.on('reaction.new', handleEvent); | |
const { unsubscribe: u4 } = client.on('reaction.deleted', handleEvent); | |
return () => { | |
u1(); | |
u2(); | |
u3(); | |
u4(); | |
}; | |
}, [threadIds]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment