Reputation: 191
I am using react-native-gifted-chat for my UI and for the backend, I am using AWSAppSync/GraphQL to store user data. I am not so sure how to go about displaying username of sender in my ChatApp and would need this feature for group chats. So far, this is my code.
import React from 'react'
import { GiftedChat } from 'react-native-gifted-chat'
class ChatScreen extends React.Component {
state = {
messages: [],
username: ''
}
componentWillMount() {
this.setState({
messages: [
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 0,
name: 'Default',
avatar: 'https://placeimg.com/140/140/any',
},
},
],
})
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
render() {
return (
<GiftedChat
messages={this.state.messages}
renderUsernameOnMessage={true}
onSend={messages => this.onSend(messages)}
user={this.username}
/>
)
}
}
export default ChatScreen;
Upvotes: 2
Views: 2847
Reputation: 5700
In react native gifted chat user
must be object containing the keys _id
, name
and avatar
. _id
will help it to separate sender and receiver. So yes, you have to set user with these properties. It not allowe only username
.
So simple way to do this is that first fetch current user info from the server and store it into redux of asyncStorage. For example I am fetching current user from firebase as below :
export const getAccountInfo = () => {
return async dispatch => {
const cu = auth().currentUser;
const user = await firestore().collection('users').doc(cu.uid).get();
dispatch({
type: Types.INFO_FETCHED,
data: user.data()
});
};
};
Now, In my chat screen I set user as below :
<GiftedChat
...
...
user={{
_id: this.props.account?.user?.uid,
name: this.props.account?.data?.fullName,
avatar: this.props.account?.data?.avatar
}}
/>
Upvotes: 1
Reputation: 174
Did you try this?
<GiftedChat
messages={this.state.messages}
renderUsernameOnMessage={true}
onSend={messages => this.onSend(messages)}
user={this.state.username}
/>
Upvotes: 2