No Description

RoomScreen.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import React, { useState, useEffect, useCallback } from 'react';
  2. import { GiftedChat } from 'react-native-gifted-chat';
  3. import firebase from 'firebase';
  4. import { connect } from 'react-redux'
  5. import { bindActionCreators } from 'redux'
  6. import { fetchUser } from '../../redux/actions/index'
  7. export function RoomScreen({ route }) {
  8. const { thread } = route.params;
  9. const [messages, setMessages] = useState([])
  10. useEffect(() => {
  11. const unsubscribe = firebase.firestore()
  12. .collection('THREADS')
  13. .doc(thread._id)
  14. .collection('MESSAGES')
  15. .onSnapshot(querySanpshot => {
  16. const messageFirestore = querySanpshot
  17. .docChanges() //para traer solo lo que haya cambiado
  18. .filter(({ type }) => type == 'added') //el objeto tiene un prop added, ese es el que queremos
  19. .map(({ doc }) => {
  20. const message = doc.data()
  21. //return { ...message, createdAt: new Date().getTime() }
  22. return { ...message, createdAt: message.createdAt.toDate() }
  23. })
  24. .sort((a, b) => b.createdAt - a.createdAt)
  25. appendMessages(messageFirestore) //Para meter el mensaje en el estado messages
  26. })
  27. return () => unsubscribe()
  28. }, [])
  29. const appendMessages = useCallback((messages) => {
  30. setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
  31. }, [messages])
  32. async function handleSend(messages) {
  33. const writes = messages.map(m => firebase.firestore()
  34. .collection('THREADS')
  35. .doc(thread._id)
  36. .collection('MESSAGES').add(m))
  37. await Promise.all(writes)
  38. }
  39. return (
  40. <GiftedChat messages={messages} user={{ _id: firebase.auth().currentUser.uid }} onSend={handleSend} />
  41. );
  42. }
  43. const mapStateToProps = (store) => ({
  44. currentUser: store.userState.currentUser,
  45. })
  46. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  47. export default connect(mapStateToProps, mapDispatchProps)(RoomScreen);