简体   繁体   中英

Updating component state by Listening to socket events inside react hooks or handling them inside middleware? what are the downsides of each one?

I have a socket class for dispatching and listening to events from the server.

The class has a method for synchronizing state between server and client .

here is how I listen to changes or events from the server.

import React, { useEffect, useState } from 'react'
import { useStore } from "./store"; // this is a zustand store object
import Game from "./game";

export const Lobby = ({ user }) => {
    const players = useStore(state => state.players);

    const dispatch = useStore(state => state.dispatch)


    const addPlayer = (player) => {
        dispatch({ type: "NEW_PLAYER", player })
    }

    useEffect(() => {
        // inside Game -> this.eventListeners[key].push(cb)
        Game.register('new-palyer', addPlayer); 
       
    }, [])

    return (
        <div>
            {
                players.map(player => <span>{player.name}</span>)
            }
        </div>
    )
}

There is another way by subscription to the store inside the Game class and updating the store with any changes. I do not implement any but before any changes to the current structure of these listeners and dispatchers, I need to make a better decision by listing the pros and cons of each paradigm. I appreciate it if answered by the real example of the middleware paradigm.

Most socket has their own event listener. For example, this is how Primus client listener works:

 primus.on('data', function (data) { if (primus.reserved(data.args[0])) return; primus.emit.apply(primus, data.args); })

I assume your socket has this kind of listener too. The best way to sync downstream data, ie: server to client, is in that handler. But for upstream data update, ie: client to server, just put the handler on component like your code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM