4

I was trying to make socket connection using React hooks. I am getting a stale value when trying to access a state variable inside socket callback function. users variable inside socket callback is not having the latest value. Using useRef works but it does not rerender the component. What could be the better solution for this ?. Thanks!

const [users, setUsers] = useState([]);
const [socket, setSocket] = useState(null);
const result = useParams();

useEffect(() => {
    const socket = io(`${config.host}?meetingId=${result.id}`);
    socket.request = promise(socket);
    setSocket(socket);
}, []);

useEffect(() => {
    if (!socket) return;
    let webrtc = null;
    
    socket.on('UserLeft', ({ id }) => {
        setUsers(users => users.filter(user => user.id !== id))
    });

    socket.on('UserAdded', ({ name, id }) => {
        const newUser = new OtherUser(name, id);
        setUsers(users => [...users, newUser])
    })

    socket.on('newProducer', async (data) => {
        const { socketId, kind } = data;

        const consumer = await webrtc.createConsumer(socketId, kind);
        
        // Issue is here, the users array still has stale values
        const user = users.find(ele => ele.id === socketId);
        
        // Some more stuff with user
    })

}, [socket]);

// Here the output is correct
console.log(users)


return <div>HELLO</div>
clickonce
  • 93
  • 2
  • 5
  • You've enclosed the *current* state in the effect into the `onUserAdd` callback. Try defining that callback outside the effect, and wrap it in a `useCallback` hook with a dependency on `users`. – Drew Reese Aug 18 '20 at 18:14
  • 1
    `useRef` seems to be the right direction. Can you add code with `useRef`? – marzelin Aug 18 '20 at 18:22
  • @DrewReese tried that, still the same issue. Thanks anyway. @marzelin tried ```useRef```. Had to do a bit of hack to re-render the component but it's working Thanks – clickonce Aug 19 '20 at 06:18

1 Answers1

0

You could use useReducer to store mutating variables and add logic into the handler