123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import React, { useState, useEffect, useCallback } from 'react';
- import { GiftedChat } from 'react-native-gifted-chat';
- import firebase from 'firebase';
- import { connect } from 'react-redux'
- import { bindActionCreators } from 'redux'
- import { fetchUser } from '../../redux/actions/index'
-
- export function RoomScreen({ route }) {
- const { thread } = route.params;
- const [messages, setMessages] = useState([])
-
- useEffect(() => {
- const unsubscribe = firebase.firestore()
- .collection('THREADS')
- .doc(thread._id)
- .collection('MESSAGES')
- .onSnapshot(querySanpshot => {
- const messageFirestore = querySanpshot
- .docChanges() //para traer solo lo que haya cambiado
- .filter(({ type }) => type == 'added') //el objeto tiene un prop added, ese es el que queremos
- .map(({ doc }) => {
- const message = doc.data()
- //return { ...message, createdAt: new Date().getTime() }
- return { ...message, createdAt: message.createdAt.toDate() }
- })
- .sort((a, b) => b.createdAt - a.createdAt)
- appendMessages(messageFirestore) //Para meter el mensaje en el estado messages
- })
- return () => unsubscribe()
- }, [])
-
-
- const appendMessages = useCallback((messages) => {
- setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
- }, [messages])
-
- async function handleSend(messages) {
- const writes = messages.map(m => firebase.firestore()
- .collection('THREADS')
- .doc(thread._id)
- .collection('MESSAGES').add(m))
- await Promise.all(writes)
- }
-
-
-
- return (
- <GiftedChat messages={messages} user={{ _id: firebase.auth().currentUser.uid }} onSend={handleSend} />
- );
- }
-
-
- const mapStateToProps = (store) => ({
- currentUser: store.userState.currentUser,
- })
- const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
- export default connect(mapStateToProps, mapDispatchProps)(RoomScreen);
|