Kavindu N
Kavindu N

Reputation: 383

Real time update with ReactJS, Redux and Websocket

This question is regarding the websocket integration with ReactJS and Redux. I’m trying to build an application where it has the ability to do real time updates. User A should see the changes which User B makes without refreshing the page.

Can you please tell me how to proceed with this implementation from the scratch and is there any other alterations for this? If there are any tutorials, please be kind enough to guide me to one of those.

Thank you

Upvotes: 4

Views: 8636

Answers (1)

TRomesh
TRomesh

Reputation: 4471

Try something like this. Since you are dealing with sockets you dont have to go through the flow of redux just use the componentDidMount() life cycle state to get real time updates.

        import React, { Component } from 'react';
        import PropTypes from 'prop-types';
        import io from 'socket.io-client';
        // should listen to your sever with socket connection in this case its localhost:3000
        let socket = io('http://localhost:3000');

     class App extends Component {

       constructor(props){
        super(props);
        this.state={
         chat:[{message:'Hello everyone'}]
        };
      }

      componentDidMount() {
        socket.on('recive', data => {
          console.log(data);
          this.setState({chat:[...this.state.chat,data]});
        })
      }

      msgthreads =()=> {
        return this.state.chat.map((msg,index)=>{
          return <div key={index} className="row message-bubble">
                    <span>{msg.message}</span>
                 </div>
        });
      }

      sendmessage =()=> {
        console.log(this.textInput.value);
        socket.emit('send',{message:this.textInput.value});
      }

      App.propTypes = {
          chat: PropTypes.array
      }

      render() {

        return (
          <div className="container">
            <div className="row">
               <div className="panel panel-default">
                 <div className="panel-heading">Panel heading without title</div>
                    <div className="panel-body">
                      <div className="container">
                          {this.msgthreads()}
                      </div>
                          <div className="panel-footer">
                            <div className="input-group">
                              <input type="text" className="form-control" ref={(input) => { this.textInput = input; }}/>
                              <span className="input-group-btn">
                                <button className="btn btn-default" type="button" onClick={this.sendmessage}>Send</button>
                              </span>
                            </div>
                          </div>
                    </div>
               </div>
            </div>
          </div>
        );
      }
    }

    export default App;

Upvotes: 5

Related Questions