Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

redux toolkit socket io

// Create class to interact with sockets
import { io, Socket } from 'socket.io-client'

export default class SocketClient {
  socket: Socket | null | undefined

  connect() {
    this.socket = io('https://localhost:8080', {
      extraHeaders: {
        Authorization: 'Bearer ...',
      },
    })
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
    }
  }

  emit(eventName: string, data: any) {
    if (this.socket) {
      this.socket.emit(eventName, data)
    }
  }

  on(eventName: string, func: () => void) {
    if (this.socket) {
      this.socket.on(eventName, func)
    }
  }
}

// -----------------------------------------------------
// When we create a store, we add middleware with socket
// -----------------------------------------------------

export const socket = new SocketClient()

export function makeStore() {
  return configureStore({
    // ...
    middleware: [socketMiddleware(socket)],
  })
}

// -----------------------------------------------------
// Track all dispatches and interact with the socket
// -----------------------------------------------------

import { Dispatch } from 'redux'
import { RootState } from 'stores/rootReducer'

// Here can be any dispatch to open a connection
const INIT_KEY = 'connect/socket'

interface SocketMiddlewareParams {
  dispatch: Dispatch
  getState: () => RootState
}

const socketMiddleware = (socket: any) => {
  return (params: SocketMiddlewareParams) => (next: any) => (action: any) => {
    const { dispatch } = params
    const { type, payload } = action

    if (type === INIT_KEY) {
      socket.connect()

      // Example ON
      socket.on('user/connect', (socketIds: any) => {
        socket.emit('sync', socketIds)
      })
    }

    switch (type) {
      // Example EMIT
      case 'user/disconnect': {
        socket.emit('joinRoom', payload.room)
        break
      }

      default:
        break
    }

    return next(action)
  }
}

// Usage
import { useDispatch } from 'react-redux'
import { useEffect } from 'react'

function MyApp() {
  const dispatch = useDispatch()
  
  useEffect(() => {
    dispatch({ type: 'socket/connect' })
  }, [])
  
  return (
    <div> Yep! </div>
  )
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: Ionic toast animation 
Typescript :: turn off suspend and sleep tagets system d 
Typescript :: laravel Adding shipping rate to checkout session results in "invalid array" exception 
Typescript :: deleting a comnent from arrays of comments in mongodb 
Typescript :: react array props typescript type 
Typescript :: Can we nested try statements in java 
Typescript :: how to checka query to return User whose first name starts with R or last name starts with D in django 
Typescript :: typescript baseurl 
Typescript :: post data 
Typescript :: Name all the elements of set Red. Use the proper set notation. 
Typescript :: TypeError: agent_go() takes 0 positional arguments but 1 was given 
Typescript :: in javaWrite a plan that prints all the perfect numbers in the range of 1 to 1000 
Typescript :: if its past 24 hrs *laravel 
Typescript :: queryselectorall of multiple tags 
Typescript :: install dependencies angular 
Typescript :: whats the internet 
Typescript :: you can initiate objects from a 
Typescript :: // running tests Your code should no longer have a p tag around the text asking what level ninja a user is. // tests completed category:423 
Cpp :: ‘setprecision’ was not declared in this scope 
Cpp :: excel vba delete worksheet if exists 
Cpp :: unreal engine delay c++ 
Cpp :: c++ print colorful 
Cpp :: rng c++ 
Cpp :: print data type of a variable in c++ 
Cpp :: double max value c++ 
Cpp :: unreal get eobjecttypequery cpp´ 
Cpp :: ue4 find component c++ 
Cpp :: tostring c++ 
Cpp :: meter espacios en cadena c 
Cpp :: 2d vector initialization in cpp 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =