Home > Net >  React Socketio won't proparly update ui
React Socketio won't proparly update ui

Time:09-17

I have an issue with react won't update ui, I am trying to update the number of people connected in the same room there's no issue in the backend, my issue is on the front because I saw that the events are reaching the client through chrome dev tools. as shown below the event is indeed reaching the client.

enter image description here

import React, { useContext, useEffect, useState, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { SocketContext } from '../context/socket';

type Props = {};

export default function Game({}: Props) {
  const socket = useContext(SocketContext);
  const { id } = useParams();

  const [playerCount, setPlayerCount] = useState(0);
  const updatePlayerCount = (...args: string[]) => {
    console.log(args);
    setPlayerCount(args.length);
  };

  useEffect(() => {
    socket.emit('join_room', id);
    socket.on('game_result', gameHandler);
    socket.on('player_count', updatePlayerCount);
    return () => {
      socket.off('game_result');
      socket.off('player_count');
    };
  }, []);

  const gameHandler = (...args: any) => {
    console.log(args);
  };

  return (
    <div>
      Game {id}
      <div>{playerCount}</div>
    </div>
  );
}

checking the console I do see my console.log firing...

enter image description here

however the first join event does work cause I don't see 0 I see 1 instead. playerCount = 0 initially

enter image description here

CodePudding user response:

You can try defining both your event handlers inside your useEffect() like this

useEffect(() => {

const updatePlayerCount = (...args: string[]) => {
    console.log(args);
    setPlayerCount(args.length);
  };

const gameHandler = (...args: any) => {
    console.log(args);
  };

    socket.emit('join_room', id);
    socket.on('game_result', gameHandler);
    socket.on('player_count', updatePlayerCount);
    return () => {
      socket.off('game_result');
      socket.off('player_count');
    };
  }, [id]);

CodePudding user response:

apparently I didn't pay attention that the data emitted was an array embedded inside an array a simple fix was

      setPlayerCount(args[0].length);
  • Related