Created
July 13, 2022 01:40
-
-
Save waldothedeveloper/c100cb1e6eec39f0e0f7b38c6b2b81f8 to your computer and use it in GitHub Desktop.
useSendAndReceiveMessages.js
This file contains hidden or 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, useState } from "react"; | |
export const useSendAndReceiveMessages = (selectedConversation) => { | |
const [conversationMessage, setConversationMessage] = useState({ | |
newMessage: ``, | |
messages: [], | |
conversationProxy: null, | |
loadingState: `initializing`, | |
}); | |
const { newMessage, conversationProxy } = conversationMessage; | |
useEffect(() => { | |
let active = true; | |
if (selectedConversation && active) { | |
// load messages for selected conversation | |
selectedConversation | |
.getMessages() | |
.then((messagePaginator) => { | |
setConversationMessage((oldData) => { | |
console.log(`I run when loading each conversation`); | |
return { | |
...oldData, | |
messages: messagePaginator.items, | |
loadingState: `ready`, | |
conversationProxy: selectedConversation, | |
}; | |
}); | |
}) | |
.catch((err) => { | |
console.log(`Couldn't not fetch messages IMPLEMENT RETRY`, err); | |
setConversationMessage((oldData) => { | |
return { | |
...oldData, | |
loadingState: `error`, | |
}; | |
}); | |
}); | |
} | |
return () => { | |
setConversationMessage((oldData) => { | |
console.log(`I just cleaned the whole damn thing`); | |
return { | |
...oldData, | |
newMessage: ``, | |
messages: [], | |
loadingState: `initializing`, | |
}; | |
}); | |
active = false; | |
}; | |
}, [selectedConversation]); | |
useEffect(() => { | |
if (conversationProxy) { | |
conversationProxy.on(`messageAdded`, (m) => { | |
setConversationMessage((oldState) => { | |
return { | |
...oldState, | |
messages: [...oldState.messages, m], | |
}; | |
}); | |
}); | |
} | |
}, [conversationProxy]); | |
const handleChange = (e) => { | |
const { value } = e.target; | |
setConversationMessage((oldData) => { | |
return { | |
...oldData, | |
newMessage: value, | |
}; | |
}); | |
}; | |
const sendMessage = async () => { | |
if (selectedConversation && newMessage) { | |
return await selectedConversation.sendMessage(newMessage); | |
} else { | |
throw new Error(`No conversation or message to send`); | |
} | |
}; | |
const handleSubmit = (event) => { | |
event.preventDefault(); | |
sendMessage() | |
.then(() => | |
setConversationMessage((oldData) => { | |
return { | |
...oldData, | |
newMessage: ``, | |
}; | |
}) | |
) | |
.catch((err) => { | |
console.log(`Couldn't not send message`, err); | |
}); | |
}; | |
return { conversationMessage, handleChange, handleSubmit }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment