I have a problem when using Math.random() from JS

I’m seeing some interesting behavior in the canister. Always the same Math.random() number when calling “http_request” using the CURL request (from Postman). However, this only works correctly when calling “readRecord” using the candid interface. But then, in subsequent calls to http_request, the last value will always be duplicated again.
I can’t figure out what could be the reason
I use Azle for my development and the result as the console output is below:

2024-06-10 20:42:43.102620663 UTC: [Canister bkyz2-fmaaa-aaaaa-qaaaq-cai] "Math.random(): " 0.7714755368394461

2024-06-10 20:42:45.853113966 UTC: [Canister bkyz2-fmaaa-aaaaa-qaaaq-cai] "Math.random(): " 0.7714755368394461

image

1 Like

A query call does not persist canister state changes. So if you do the second query call, it will do the same as if the first one didn’t happen. If you make an update call in between, this may (accidentally) advance the PRNG so that the next query will have a new starting state

1 Like

This sounds like it’s true )
just call some method? and what method can be called?
Ideally, I would like to call createRecord from http_request, but I didn’t figure out how to do this and thought that this was impossible. Therefore, from both of these methods I call the “createRecord()” function to save records in StableBTreeMap.
I will be very grateful for your help )

1 Like

Here is how you can change from query http_request to update http_request_update where you can then createRecord()

And just to get back to randomness again: It’s probably best if you pretend you don’t have access to randomness (or at lest not unbiased randomness) in query calls

1 Like

I wanted to clarify that I cannot call the “http_request_update” method from Postman, since I need to sign requests. So, I should use dfx or agent

1 Like

I just wanted to concur, randomness only advances from update calls.

I also wanted to recommend that you just do a full server canister. You could then use fetch from a web frontend using Azle’s toJWT authentication mechanism to authenticate to your endpoints, and you could just use Express or NestJS.

https://demergent-labs.github.io/azle/servers.html

It’s more experimental but much simpler and more similar to the traditional web developer experience.