I'm using Gifted Chat for a chat app using React Native. When I send either a text message or an image, the code executes, but the new message does not appear on the screen unless I scroll to the top of the chat screen. If I scroll to the bottom, nope, and if I only scroll halfway up, still nope. Only when I scroll to the top of the screen does it update. Anyone understand why this could be happening? Here is my code.
import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, Button, FlatList, TouchableOpacity, Alert } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
const Conversation = (props) => {
const chatId = props.chatId || "12345";
const userId = props.userId || "6789";
const [messages, setMessages] = useState([
{
_id: 1,
text: 'My message',
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
user: {
_id: userId,
name: 'Jane',
avatar: 'https://randomuser.me/api/portraits/women/79.jpg',
}
},
{
_id: 3,
text: 'My next message',
createdAt: new Date(Date.UTC(2016, 5, 11, 17, 21, 0)),
user: {
_id: 4,
name: 'Gerry',
avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
},
image: 'https://media1.giphy.com/media/3oEjHI8WJv4x6UPDB6/100w.gif',
}
]);
const d = Date.now();
const onSend = (msg) => {
console.log("msg : ", msg);
const message = {
_id: msg[0]._id,
text: msg[0].text,
createdAt: new Date(),
user: {
_id: userId,
avatar: "https://randomuser.me/api/portraits/women/79.jpg",
name: "Jane"
}
}
const arr = messages;
arr.unshift(message);
setMessages(arr);
}
return (
<GiftedChat
messages={messages}
onSend={newMessage => onSend(newMessage)}
user={{
_id: userId,
name: "Jane",
avatar: "https://randomuser.me/api/portraits/women/79.jpg"
}}
/>
)
}
export default Conversation;
Figured it out. GiftedChat requires that you use one of its own methods called append
.
const onSend = (msg) => {
console.log("msg : ", msg);
// first, make sure message is an object within an array
const message = [{
_id: msg[0]._id,
text: msg[0].text,
createdAt: new Date(),
user: {
_id: userId,
avatar: "https://randomuser.me/api/portraits/women/79.jpg",
name: "Jane"
}
}]
// then, use the GiftedChat method .append to add it to state
setMessages(previousArr => GiftedChat.append(previousArr, message));
}