-
Notifications
You must be signed in to change notification settings - Fork 1
Step 1
Isaac Pak edited this page Dec 1, 2017
·
1 revision
You will need to have an instance of socket.io on the client side. We will be using the npm module socket.io-client to create one and the following client. This could probably go under your services layer in your app. Here is what that could look like:
// app root
// services
// socketio
// index.js
An example client:
import io from 'socket.io-client'
import {Component} from 'react'
const socketPath = '/api/socket.io'
class Socket {
connect() {
this.socket = io()
return new Promise((resolve, reject) => {
this.socket.on('connection', nsp => {
// return state of socket in redux
})
this.socket.on('connect_error', error => reject(error))
})
}
disconnect() {
return new Promise(resolve => {
this.socket.disconnect(() => {
this.socket = null
resolve()
})
})
}
emit(event, data) {
return new Promise((resolve, reject) => {
if (!this.socket) return reject('No socket connection.')
return this.socket.emit(event, data, response => {
// Response is the optional callback that you can use with socket.io in every request. See 1 above.
if (response.error) {
console.error(response.error)
return reject(response.error)
}
return resolve()
})
})
}
on(event, fun) {
// No promise is needed here, but we're expecting one in the middleware.
return new Promise((resolve, reject) => {
if (!this.socket) return reject('No socket connection.')
this.socket.on(event, fun)
resolve()
})
}
}
export default Socket