Home > Net >  react prop passing to child component only works with localhost backend
react prop passing to child component only works with localhost backend

Time:05-29

I'm kinda losing my mind as I have no idea what is the problem or how to approach it. I have the same files in in my backend server (hosted on heroku) and local directory and the same goes for the frontend

const SOCKET_SERVER_URL = 'https://backendserverurl.com';
// const SOCKET_SERVER_URL = 'http://localhost:5000';

I'm trying to set the useState by listening to a socket event listener

(both local backend server and heroku server receives the data from socket listener "currentRoom")

const [myRoom, setMyRoom] = useState(null)
...
...
...
        socket.on("currentRoom", (args) => {
            setMyRoom(args)
            console.log("logging inside lobby ")
            console.log(args)
        });

and pass it to a child component under return.

return (
    ...
    <Game socket={socket} setInLobby={setInLobby} roomPlayers={roomPlayers} room={myRoom} />
    ...
)

Inside the child component: "Game" is able to receive the room prop when I'm using localhost as the backend but no data is passed on when I'm using the hosted backend as the SOCKET_SERVER_URL.

const Game = ({ socket = null, setInLobby = null, roomPlayers = null, room = null }) => {
    ...
    ...
    // logs the room if the backend is localhost but is null when backend is hosted online
    console.log(room)
    ...
    ...
)}

I'd understand if there's a problem with the frontend but I'm not sure why the useState variable is not able to be passed as a prop if the backend is not local hosted.

Please let me know if you require more information. Thank you

CodePudding user response:

return (
    ...
    {(!inLobby && myRoom) &&
    <Game socket={socket} setInLobby={setInLobby} roomPlayers={roomPlayers} room={myRoom} />
    }
    ...
)

Oops, it turns out the delay added when the hosted backend is used is too slow for the data to be fetched to the frontend.

Adding

{(!inLobby && myRoom) &&
...
}

To wait for the data to be received fixed the problem

  • Related