No Description

RoomScreen.js 1.8KB

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