1

I am trying to build a chat feature for my application using React Native + Gifted Chat + expo + firebase realtime DB. I could build the module upto this part. I am using Firebase authentication and was wondering how can I associate these chats with the credentials of the user sending and receiving them - so that when they log back in - they can see their past chats and can know who sent them. It is only a one way chat as of now and I have just hardcoded one message and a user email id - but I want it to like :

user 1 logs in - sends 'Hi' to user 2

user 2 logs in and sees all past messages with User 1 and the new 'Hi' part.

I have added the previousState part of the code to append old messages - but it's not happening as I havent associated the current user with the chats till now.

Any idea on how to do it ? Help will be EXTREMELY appreciated !

just one way chat as of now

I am authenticating using the Firebase Authentication :

  Login = (email, password) => {
    try {
      firebase
         .auth()
         .signInWithEmailAndPassword(email, password)
         .then(res => {
             console.log(res.user.email);
             this.props.navigation.navigate('MainMenu');
          })
} catch (error) {
      console.log(error.toString(error));
    }
  };

Code of my current Chat is as follows :

let saveMessage = message => {
  db.ref('/messages').push({
    messageText: message
  });
};  

class ChatPage extends React.Component {

    state = {[![right now its just one-way chat - and no saving od ][1]][1]
      messages: []
    };

    componentDidMount() {
      this.setState({
        messages: [ 
          {
            _id: 1,
            text: "Hi there, how are you doing ?",
            createdAt: new Date(),
            user: {  
              _id: 2,
              name: "user1@gmail.com",
              avatar: "https://placeimg.com/640/480/nature"
            }
          }
        ]
      });
    }

    onSend(messages = []) {
      this.setState(previousState => ({
        messages: GiftedChat.append(previousState.messages, messages),
      }))
      db.ref('/messages').push({ messages });
    }

    render() {
      return (<KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior="padding"
        keyboardVerticalOffset={Platform.select({
          ios: () => 0,
          android: () => 100
        })()}
      ><GiftedChat 
      messages={this.state.messages}         
      onSend={messages => this.onSend(messages)}
      // user={{
      //   _id: 1,
      // }}
      user={this.state.email}
      renderUsernameOnMessage={true}

      /></KeyboardAvoidingView>)
    } 


  }

Suman Shaw
  • 133
  • 3
  • 10
  • Were you able to solve this issue? I am about to add gifted chat to my app and using firestore instead of realtime database. Any help would be appreciated! – kalculated Jan 20 '21 at 03:57

0 Answers0