|
|
@@ -1,4 +1,4 @@
|
|
|
-import { useState, useEffect, useRef } from 'react'
|
|
|
+import { useState, useCallback, useEffect } from 'react'
|
|
|
import { ChatStore } from './chat-store'
|
|
|
import { useApplicationContext } from '../../../shared/context/application-context'
|
|
|
import { useEditorContext } from '../../../shared/context/editor-context'
|
|
|
@@ -7,29 +7,32 @@ export function useChatStore() {
|
|
|
const { user } = useApplicationContext()
|
|
|
const { projectId } = useEditorContext()
|
|
|
|
|
|
- const chatStoreRef = useRef(new ChatStore(user, projectId))
|
|
|
+ const [atEnd, setAtEnd] = useState(false)
|
|
|
+ const [loading, setLoading] = useState(false)
|
|
|
+ const [messages, setMessages] = useState([])
|
|
|
|
|
|
- const [atEnd, setAtEnd] = useState(chatStoreRef.current.atEnd)
|
|
|
- const [loading, setLoading] = useState(chatStoreRef.current.loading)
|
|
|
- const [messages, setMessages] = useState(chatStoreRef.current.messages)
|
|
|
+ const [store] = useState(() => new ChatStore(user, projectId))
|
|
|
+ const loadMoreMessages = useCallback(() => store.loadMoreMessages(), [store])
|
|
|
+ const sendMessage = useCallback(message => store.sendMessage(message), [
|
|
|
+ store
|
|
|
+ ])
|
|
|
|
|
|
useEffect(() => {
|
|
|
- const chatStore = chatStoreRef.current
|
|
|
function handleStoreUpdated() {
|
|
|
- setAtEnd(chatStore.atEnd)
|
|
|
- setLoading(chatStore.loading)
|
|
|
- setMessages(chatStore.messages)
|
|
|
+ setAtEnd(store.atEnd)
|
|
|
+ setLoading(store.loading)
|
|
|
+ setMessages(store.messages)
|
|
|
}
|
|
|
- chatStore.on('updated', handleStoreUpdated)
|
|
|
- return () => chatStore.destroy()
|
|
|
- }, [chatStoreRef])
|
|
|
+ store.on('updated', handleStoreUpdated)
|
|
|
+ return () => store.destroy()
|
|
|
+ }, [store])
|
|
|
|
|
|
return {
|
|
|
userId: user.id,
|
|
|
atEnd,
|
|
|
loading,
|
|
|
messages,
|
|
|
- loadMoreMessages: () => chatStoreRef.current.loadMoreMessages(),
|
|
|
- sendMessage: message => chatStoreRef.current.sendMessage(message)
|
|
|
+ loadMoreMessages,
|
|
|
+ sendMessage
|
|
|
}
|
|
|
}
|