No Description

RoomScreen.js 3.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 { currentUser } = props;
  9. const { thread } = route.params;
  10. /*const [messages, setMessages] = useState([
  11. /**
  12. * Mock message data
  13. */
  14. // example of system message
  15. /* {
  16. _id: 0,
  17. text: 'New room created.',
  18. createdAt: new Date().getTime(),
  19. system: true
  20. },
  21. // example of chat message
  22. {
  23. _id: 1,
  24. text: 'Henlo!',
  25. createdAt: new Date().getTime(),
  26. user: {
  27. _id: 2,
  28. name: 'Test User'
  29. }
  30. }
  31. ]);*/
  32. const [messages, setMessages] = useState([])
  33. /** the useEffect is used when we first render the component
  34. * solo va a corrar al principio.
  35. */
  36. useEffect(() => {
  37. //readUser()
  38. const unsubscribe = firebase.firestore()
  39. .collection('THREADS')
  40. .doc(thread._id)
  41. .collection('MESSAGES')
  42. .onSnapshot(querySanpshot => {
  43. const messageFirestore = querySanpshot
  44. .docChanges() //para traer solo lo que haya cambiado
  45. .filter(({ type }) => type == 'added') //el objeto tiene un prop added, ese es el que queremos
  46. .map(({ doc }) => {
  47. const message = doc.data()
  48. return { ...message, createdAt: new Date().getTime() }
  49. })
  50. .sort((a, b) => b.createdAt - a.createdAt)
  51. appendMessages(messageFirestore) //Para meter el mensaje en el estado messages
  52. })
  53. return () => unsubscribe()
  54. }, [])
  55. const appendMessages = useCallback((messages) => {
  56. setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
  57. }, [messages])
  58. async function handleSend(messages) {
  59. const writes = messages.map(m => firebase.firestore()
  60. .collection('THREADS')
  61. .doc(thread._id)
  62. .collection('MESSAGES').add(m))
  63. await Promise.all(writes)
  64. }
  65. /*async function handleSend(messages, newMessage = []) {
  66. const text = messages[0].text;
  67. setMessages(GiftedChat.append(messages, newMessage));
  68. //aqui podemos usar current user que no lo hemos usado, ya tenemos conectado redux
  69. firebase.firestore()
  70. .collection('Users')
  71. .doc(firebase.auth().currentUser.uid)
  72. .collection('THREADS')
  73. .doc(thread._id)
  74. .collection('MESSAGES')
  75. .add({
  76. text,
  77. createdAt: new Date().getTime(),
  78. });
  79. //Esto se ve, pero no genraliza, solo funciona desde currentUser y se graba en la otra cuenta,
  80. //pero la otra cuenta no puede responder porque pasa a ser current user.
  81. //Ademas no guarda que usuario dijo que.
  82. firebase.firestore()
  83. .collection('Users')
  84. .doc('HGGAJlcIfwdpUoYfcBKLZFcDude2')
  85. .collection('THREADS')
  86. .doc(thread._id)
  87. .collection('MESSAGES')
  88. .add({
  89. text,
  90. createdAt: new Date().getTime(),
  91. });
  92. }*/
  93. // helper method that is sends a message
  94. /*function handleSend(newMessage = []) {
  95. setMessages(GiftedChat.append(messages, newMessage));
  96. }*/
  97. return (
  98. /*<GiftedChat
  99. messages={messages}
  100. onSend={newMessage => handleSend(messages, newMessage)}
  101. user={{ _id: 1 }}
  102. showUserAvatar
  103. alwaysShowSend
  104. scrollToBottom
  105. />*/
  106. <GiftedChat messages={messages} user={{ _id: 1 }} onSend={handleSend} />
  107. );
  108. }
  109. const mapStateToProps = (store) => ({
  110. currentUser: store.userState.currentUser,
  111. })
  112. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  113. export default connect(mapStateToProps, mapDispatchProps)(RoomScreen);