stale state inside socket callback

Viewed 272

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>
1 Answers

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

Related