SHARE
TWEET

Untitled

a guest Sep 12th, 2019 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { Component } from 'react';
  2.  
  3. import { ROOM_FETCH } from '../actions';
  4. import connection from '../lib/socket';
  5.  
  6. import Messages from '../components/Messages';
  7. import AddMessage from '../components/AddMessage';
  8.  
  9. // a global variable so we can disconnect once we unmount
  10. let subscription;
  11.  
  12. class Room extends Component {
  13.   state = {
  14.     messages: []
  15.   };
  16.  
  17.   componentDidMount () {
  18.     connection.connect();
  19.  
  20.     // storing the subscription in the global variable
  21.     // passing the incoming data handler fn as a second argument
  22.     subscription = connection.subscribe(`room:${this.props.id}`, this.handleMessageAdd);
  23.  
  24.     // loading existing messages
  25.     this.fetchMessages();
  26.   }
  27.  
  28.   componentWillUnmount () {
  29.     subscription.close();
  30.   }
  31.  
  32.   handleMessageAdd = message => {
  33.     const { type, data } = message;
  34.  
  35.     // you could handle various types here, like deleting or editing a message
  36.     switch (type) {
  37.       case 'room:newMessage':
  38.         this.setState(prevState => ({
  39.           messages: [...prevState.messages, data]
  40.         }));
  41.         break;
  42.       default:
  43.     }
  44.   };
  45.  
  46.   fetchMessages = async () => {
  47.     try {
  48.       const room = await ROOM_FETCH(this.props.id);
  49.       this.setState({ messages: room.messages });
  50.     } catch (_) {
  51.       this.props.history.push('/');
  52.     }
  53.   };
  54.  
  55.   render () {
  56.     const { messages } = this.state;
  57.     const { id } = this.props;
  58.  
  59.     return (
  60.       <div className="mx-auto p-3 flex flex-col h-screen justify-between" style={{ maxWidth: '800px' }}>
  61.         <Messages data={messages} />
  62.         <AddMessage roomId={id} />
  63.       </div>
  64.     )
  65.   }
  66. }
  67.  
  68. export default Room;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top