chat-store-effect.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { useState, useCallback, useEffect } from 'react'
  2. import { ChatStore } from './chat-store'
  3. import { useApplicationContext } from '../../../shared/context/application-context'
  4. import { useEditorContext } from '../../../shared/context/editor-context'
  5. export function useChatStore() {
  6. const { user } = useApplicationContext()
  7. const { projectId } = useEditorContext()
  8. const [atEnd, setAtEnd] = useState(false)
  9. const [loading, setLoading] = useState(false)
  10. const [messages, setMessages] = useState([])
  11. const [store] = useState(() => new ChatStore(user, projectId))
  12. const loadMoreMessages = useCallback(() => store.loadMoreMessages(), [store])
  13. const sendMessage = useCallback(message => store.sendMessage(message), [
  14. store
  15. ])
  16. useEffect(() => {
  17. function handleStoreUpdated() {
  18. setAtEnd(store.atEnd)
  19. setLoading(store.loading)
  20. setMessages(store.messages)
  21. }
  22. store.on('updated', handleStoreUpdated)
  23. return () => store.destroy()
  24. }, [store])
  25. return {
  26. userId: user.id,
  27. atEnd,
  28. loading,
  29. messages,
  30. loadMoreMessages,
  31. sendMessage
  32. }
  33. }