Search code examples
javascriptreactjsnext.jsnext-router

How do I dynamically create route using a function return in next.js


I am trying to create a simple multiplayer game. I want to use a randomly generated room id in the route in order to route to the newly created lobby but can not pass the functions return to router.push as query ; I don't know why? Can you help me?

const RandomRoom = () =>{
        let romstr = "";

        for(let i=0; i<5; i++){
            const randomElement = randomchars[Math.floor(Math.random() * randomchars.length)];

            romstr += randomElement;

        }
        return romstr;
    }
    const handleSubmit = function () {

        return function () {
            if (!executed) {

                const param = RandomRoom;

                executed = true;

                socket.emit("joinroom", data1);

                console.log("roomid" + param);

                router.push({
                    pathname: `/lobby/[lobbyid]`,
                    query: {param}
            });
            }
        }
    }()

Solution

  • There's an issue with your router.push method, you do not provide lobbyid property to your query object.

    const param = RandomRoom;
    
    router.push({
      pathname: '/lobby/[lobbyid]',
      query: { lobbyid: param },
    });