tajihiro
tajihiro

Reputation: 2443

Design for Websocket with React + Redux

I am trying to implement Websocket communication with React + Redux. The question is kind of design of scope.

The following code is part of source code I wrote.

In this page, 1. Init Socket Settings ⇒ 2. Start Socket ⇒ 3. Execute Event ⇒ 4. Receive Socket

When I execute event, I can receive the websocket data, however I have no idea how to locate these method for the best.

My question is I would like to know the best practice of design. Of corse, I would like to make use of the design of Redux. If you have better idea, it doesn't matter to use other modules like reducer or actions.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Socket } from 'phoenix';

//Init Socket Settings 
const socket = new Socket("/socket", {params: {token: window.userToken}});
socket.connect();
const channel = socket.channel("member:lobby", {});

//Receive Socket 
channel.on('new_message', state => {
    console.log("Receive Socket!!!" + state.body);
});


class Sample extends Component{
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }

        this.doEnterKey = this.doEnterKey.bind(this);
    }

    componentDidMount() {
        //Start Socket
        channel.join()
            .receive("ok", resp => { console.log("Joined successfully", resp) })
            .receive("error", resp => { console.log("Unable to join", resp) })
    }

    //Execute Event
    doEnterKey(e){
        if(e.keyCode === 13){
            console.log('Enter Key!!!' + e.target.value);
            channel.push("new_message", {body: e.target.value});
        }
    }

    render() {
        return (
            <div>
                <div>Websocket</div>
                <div id="messages"></div>
                <input id="chat-input" type="text" onKeyDown={this.doEnterKey}></input>
            </div>
        );
    }
}
export default connect()(Sample);

Where is the best place to location for socket and channel?

Upvotes: 1

Views: 778

Answers (1)

SM Chinna
SM Chinna

Reputation: 341

Here if you need to store web socket details to the redux.

  1. Create action and reducer
  2. Call the action on the receive function with response data.
  3. Update the reducer.

Upvotes: 1

Related Questions