AutorÃa | Ultima modificación | Ver Log |
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { getConversations } from '@app/services/chats'
import { addNotification } from '@app/redux/notification/notification.actions'
export function useConversations(url) {
const [conversations, setConversations] = useState([])
const [currentConversation, setCurrentConversation] = useState(null)
const [loading, setLoading] = useState(false)
const dispatch = useDispatch()
const heartBeat = async (url) => {
setLoading(true)
try {
const results = await getConversations(url)
if (JSON.stringify(conversations) !== JSON.stringify(results)) {
setConversations(results)
}
} catch (error) {
dispatch(addNotification({ style: 'danger', msg: error.message }))
} finally {
setLoading(false)
}
}
const setConversation = (conversation) => {
setCurrentConversation(conversation)
}
useEffect(() => {
const conversationsInterval = setInterval(() => {
heartBeat(url)
}, 2000)
return () => {
clearInterval(conversationsInterval)
}
}, [url, conversations])
return {
conversations,
currentConversation,
setConversation,
loading
}
}