0

I am having problem of react-native-gifted-chat by using cloud firestore. I am unable to fetch previous messages and append to the gifted chat. please show me the code that how it is used with the cloud firestore. thanks

  • This user from this [Stackoverflow issue](https://stackoverflow.com/questions/58033547/convert-all-array-objectfirestore-timestamp-to-date) claimed to have fixed their issue using react-native-gifted-chat. If you look closely, you'll see sample code for fetching messages that may be useful for your own application. Also you can check this [GitHub repo](https://github.com/FaridSafi/react-native-gifted-chat). Keep me posted. – sllopis Oct 17 '19 at 08:13

1 Answers1

1

I have been able to get this to work on my app using a similar method to that found at GitHib repo

My code calls a loadMessages function in componentDidMount which uses onSnapshot to keep track of any changes in my Message or Chats collections. If a change occurs it uses a callback function to append the new messages to GiftedChat.

Here is my code:

async componentDidMount() {    
    this.loadMessages(message => {
      this.setState(previousState => {
        return {
          messages: GiftedChat.append(previousState.messages, message)
        };
      });
    });

  }
async loadMessages(callback) {
    var that = this;
    var recipientId = this.props.navigation.getParam("recipientId");
    var chatId = this.generateChatID(recipientId);

    this.setState({ chatId });
    firebase
      .firestore()
      .collection("Message")
      .doc(chatId)
      .collection("Chats")
      .orderBy("createdAt", "asc")
      .onSnapshot(function(doc) {
        doc.docChanges().forEach(chat => {
          var id = chat.doc.id;
          chat = chat.doc.data();
          const newMessage = {
            _id: id,
            text: chat.text,
            createdAt: chat.createdAt.toDate(),
            user: {
              _id: chat.user._id,
              name: chat.user.name,
              avatar: chat.avatar
            }
          };
          callback(newMessage);
        });
      });
  }

Lmk if you have any questions!

Joshua Zeltser
  • 488
  • 2
  • 9
  • can you please share me the code link that how do you handle the chat, or screenshots of the data structure you have used in firestore? – F. Hayat Jadoon Dec 13 '19 at 12:25