GitHub Documentation

How to access the current room in Redux?



  • Hey all, has anyone managed to implement Colyseus with Redux a React client? I'm having an issue where I don't know how to access the room instance from outside the function that created/joined it. For example, I have a thunk to create a room,

    export const createRoomAsync = (options = {}) => (dispatch) => {
      return colyseus.create("room_name", options).then((room) => {
        // Update the local store
        dispatch(joinRoom({ id: room.id }));
        // Redirect the user to the room
        dispatch(push(`/room/${room.id}`));
    
        return room;
      });
    };
    

    and then another one to leave the room

    export const leaveRoomAsync = () => async (dispatch) => {
      // Leave the room - how to access the room instance?
      // room.leave();
    
      // Update the store
      dispatch(leaveRoom());
      // Send the user home
      dispatch(push("/"));
    };
    

    With Redux you cannot store non-serialisable objects in the store, so I can't store room in the store with all its methods when created. So how do I access the room instance outside of the function that created it?
    Ideally, I'd like to call a method like colyseus.getCurrentRoom() , but nothing like seems to exist in the API.
    Any help would be appreciated!



  • what i did was create a new Helper class file (Javascript Class), then added all the Colyseus functionalities and listeners and everything there. so I can store the room in a variable there like this.room which can be accessed from any other component on my whole application.

    class ActivityRoom {
        constructor() {
            this.client = new Colyseus.Client(clientUrl);
        }
    
        connect = async (username, rating, photoUrl) => {
            this.name = username;
            this.rating = rating;
            this.photoUrl = photoUrl;
            try {
                const room = await this.client.joinById('AR1', {
                    username,
                    rating,
                    photoUrl
                });
                this.room = room;
                this.sessionId = room.sessionId;
                this.Room_Listeners();
            } catch (error) {}
            console.error(error);
        }
    };
    
    leaveRoom() {
        this.room.leave();
    }
    }
    

    then call the leaveRoom like ActivityRoom.leaveRoom from any other Component i want.


 

© 2020 Endel Dreyer