Is there a way to achieve one to one messaging in react native with firebase real time database?

604 Views Asked by At

I am trying to achieve one-to-one messaging in react native using the firebase real time database. I am very new to react native/firebase and I am not too sure how I can send a message to a specific user uid. I have seen a few links online which uses firebase firestore for group chats but I would like to perform this using the real time database and only one-to-one messaging. So far I have managed to send a message in my app but I am displaying all messages from all users from the database too when logged in as the current user. I am using react-native-gifted-chat for the UI.

// This is file MessagesScreen.js

class MessagesScreen extends Component {
  state = {
    messages: []
  }  

  get user() {
    return {
      _id: FireMessage.uid,
    }
  }

  componentDidMount() {
    FireMessage.get(message => this.setState(previous => ({
      messages: GiftedChat.append(previous.messages, message)
    })));
  }

  componentWillUnmount() {
    FireMessage.off();
  }

  render() {
    const chat = <GiftedChat messages={this.state.messages} onSend={FireMessage.send} user={this.user} />;

    if (Platform.OS === "android") {
      return (
        <KeyboardAvoidingView style={{ flex: 1}} behavior="padding" keyboardVerticalOffset={10} enabled>
          {chat}
        </KeyboardAvoidingView>
      );
    }

    return <SafeAreaView style={{ flex: 1}}>{chat}</SafeAreaView>;
  }
}

export default MessagesScreen;
// This is file FireMessage.js

class FireMessage {

  constructor() {
    this.init()
    this.checkAuth() 
  }

  init = () => {
    if (!firebase.apps.length && firebaseConfig.apps.length === 0) {
      firebase.initializeApp({
        apiKey: "xxxxxxxxxxx",
        authDomain: "xxxxxxxxxxx",
        databaseURL: "xxxxxxxxxx",
        projectId: "xxxxxxxx",
        storageBucket: "xxxxxxxxxx",
        messagingSenderId: "xxxxxxxx",
        appId: "xxxxxxxxxxx",
        measurementId: "xxxxxxxxx"
      });
    }
  };

  checkAuth = () => {
    firebase.auth().onAuthStateChanged(user => {
      if (!user) {
        firebase.auth().signInAnonymously();
      }
    });
  };

  send = messages => {
    messages.forEach(item => {
      const message = {
        text: item.text,
        timestamp: firebase.database.ServerValue.TIMESTAMP,
        user: item.user
      };

      this.db.push(message)
    });
  };

  parse = message => {
    const { user, text, timestamp } = message.val();
    const { key: _id } = message;
    const createdAt = new Date(timestamp);


    return {
      _id,
      createdAt,
      text,
      user
    };
  };
 
  get = callback => {
    this.db.on("child_added", snapshot => 
      callback(this.parse(snapshot)));
  };

  off() {
    this.db.off();
  }

  get db() {
    return firebase.database().ref("messages");
  }

  get uid() {
    return (firebase.auth().currentUser || {}).uid;
  }
}

export default new FireMessage();

Realtime Database structure:

Database structure of messages

Database structure of users

0

There are 0 best solutions below