Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Socket.io with ReactJS ES6

I'm having trouble incorporating SocketIO client into my project as I have me project set up isomorphically. After including the socket file in my base html, I try to call let socket = io(); in the componentdidmount of one of my components however initially after logging it in my console it is undefined. When I route to a different component and comeback to that component with that socket variable then it becomes filled with some data. I guess my point here it isn't initializing in my component what socket is, it seems like it has to wait how do I work around this?

Component.jsx

componentDidMount() {
    let socket = io();
    console.log(socket);
  }

Base.html

<!doctype html>
<html lang="">

<head>
    <title>TITLE</title>

    META

    LINK

</head>

<div class="app">CONTENT</div>

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-XXXXX-X', 'auto');
    ga('send', 'pageview');
</script>
<script type="text/javascript" charset="utf-8" src="/assets/app.js"></script>

<script src="/socket.io/socket.io.js"></script>
<script>
        var socket = io();
</script>

</body>
</html>

This works fine btw I for stuff like on connect from the server, it emits that a user is connecting and disconnecting off the server, just the client manipulation has me puzzled.

like image 622
Karan Avatar asked Dec 27 '15 13:12

Karan


People also ask

Is Socket.IO an API?

Server API | Socket.IO.

Is Socket.IO using WebSocket?

Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.


2 Answers

There are likely other solutions, but the following works for me:

1) npm install the socket client side package

2) import socket into the most root component of all components that need socket functionality

3) hookup server side socket event listeners in one of the lifecycle events (constructor / componentWillMount, componentDidMount)

4) pass down socket object through props if it makes sense to handle certain server events in child components

example:

import io from 'socket.io-client'
let socket = io(`http://localhost:8000`)

class App extends Component {
  state = { data: {} }

  componentDidMount() {    
    socket.on(`server:event`, data => {
      this.setState({ data })
    })
  }

  sendMessage = message => {
    socket.emit(`client:sendMessage`, message)
  }

  render () {
    return (
      <Child 
        socket = { socket } 
        sendMessage = { this.sendMessage }
      />
    )
  }
}
like image 145
azium Avatar answered Oct 15 '22 11:10

azium


You can instantiate a socket outside of the component and use it inside the component. Like this:

import React, { Component } from 'react'  
import io from 'socket.io-client'

var socket = io()

class MyComponent extends Component {
    componentDidMount() {
        // You can use the socket inside the componet
        socket.on('message', msg => console.log(msg))
    }
}
like image 31
gedhean Avatar answered Oct 15 '22 10:10

gedhean