SolidJSS
SolidJS13mo ago
4 replies
Zikado

Different server context when using "use server"?

Hi, I was trying to create a simple game project where player lobbies would (for simplicity) be saved on the server. Then I wanted to create some RPC using the "use server" so I can for example check whether the specific lobby exists etc.

But I encountered that the state of the variable differed in the RPC functions and the rest of the server context, let me show an example on random number variable.

src/server/number.ts
export const randomNumber = Math.random();


Then I created API endpoints just to be able to easily check whether the numbers match

src/routes/api/getRandomNumber.ts
import type { APIEvent } from "@solidjs/start/server";
import { randomNumber } from "~/server/lobby";

export async function GET() {
  console.log(randomNumber);
  return "ok";
}


This is the RPC for getting the random number

src/routes/utils/callbacks.ts
"use server";

import { randomNumber } from "~/server/number";

export const getRandomNumber = async () => {
  console.log(randomNumber);
};


Lastly I have a page where I get the data from both sources so I can check whether they match

import { getRandomNumber } from "~/utils/callbacks";

export default function Page() {
  const handleClick = () => {
    getRandomNumber();
    fetch("/api/getLobbies");
  };

  return <button on:click={handleClick}>Click</button>;
}


And this was the result:
RPC: 0.7921163507084992
API: 0.4117746060818235

This probably comes from my lack of knowledge but I would really appreciate any explanation why does it behave that way and what is the proper way to handle it/change it to more suitable solution.

Thank you in advance.
Was this page helpful?