Skip to content

Instantly share code, notes, and snippets.

@hieptl
Last active October 15, 2021 12:30
Show Gist options
  • Save hieptl/1c2d21089532e07d3d673b76d18173db to your computer and use it in GitHub Desktop.
Save hieptl/1c2d21089532e07d3d673b76d18173db to your computer and use it in GitHub Desktop.
Chat.js - Send Message - React Native Gifted Chat App
...
const Chat = () => {
...
const { cometChat, selectedConversation, user} = useContext(Context);
const [messages, setMessages] = useState([]);
...
const getReceiverId = () => {
if (selectedConversation && selectedConversation.guid) {
return selectedConversation.guid;
}
if (selectedConversation && selectedConversation.uid) {
return selectedConversation.uid;
}
return null;
};
const getReceiverType = () => {
if (selectedConversation && selectedConversation.guid) {
return cometChat.RECEIVER_TYPE.GROUP;
}
return cometChat.RECEIVER_TYPE.USER;
};
const sendMessageCometChat = (messages) => {
if (messages && messages.length !== 0) {
const receiverID = getReceiverId();
const receiverType = getReceiverType();
if (receiverID && receiverType) {
const messageText = messages[0].text;
const textMessage = new cometChat.TextMessage(
receiverID,
messageText,
receiverType
);
cometChat.sendMessage(textMessage).then(
message => {
setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
},
error => {
}
);
}
}
};
const onSend = useCallback((messages = []) => {
sendMessageCometChat(messages);
}, []);
...
return (
<>
<View style={{ backgroundColor: '#fff', flex: 1 }}>
<GiftedChat
...
onSend={messages => onSend(messages)}
...
/>
</View>
</>
)
...
};
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment