redux toolkit socket io
The solution for “redux toolkit socket io” can be found here. The following code will assist you in solving the problem.
// 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 (
Yep!
)
}
More questions on [categories-list]
- tss from gene granges
- ixl ansers ixl ansers
- get coin prices node-binance
- how to setup netflix workflow worker
- spritesheets in pyqt spritesheets in pyqt
- cahokia mounds pictures cahokia mounds pictures cahokia mounds pictures
- python 2 decimal places how to get decimal part of a double in python set number of decimals python
- how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python
- haskell get specific elements of a String
- vb net code snippets for storing password
- error TS2307: Cannot find module ‘@ngx-meta/core’.
- inline scripts encapsulated in tags