[Q] How to create cookies with dynamic `name` (name of the cookie on client side)
Hi. I am trying to create cookies using rx.Cookie. So far, I have not faced any issues with cookies that have fixed name parameter value while initializing rx.Cookie as a state variable.
# Working code
class MyState(rx.State):
....
x: str = rx.Cookie(
max_age=config.cookies_max_age,
name="x", # fixed `name` parameter
secure=True,
same_site="strict",
path="/",
)
....
But if I try to do this with dynamic / changing cookie name (the name at client side), cookie keys and values are not being written to document.cookie.
# Buggy code
class MyState(rx.State):
x: Optional[str] = None
def create_cookie(self, cookie_name: str) -> None:
# this code will run one time only (if x is `None` or if `cookie_name` doesn't exist in client side
my_cookie_name = f"x_{cookie_name}"
self.x: str = rx.Cookie(
max_age=config.cookies_max_age,
name=my_cookie_name ,
secure=True,
same_site="strict",
path="/",
)
# Handles google login callback
class MyGoogleLoginCallbackHandlerState(MyState):
....
....
....
def handle_callback(self):
....
....
....
if not self.x:
cookie_name = "page1_cookie" # I NEED to set different cookie name for different pages / routes
self.create_cookie(cookie_name)
self.x= jwt.encode(...)
If I use above code, I can see that jwt string is written MyState.x (confirmed by displaying it in rx.Component) but it is not being written to document.cokkies in the browser i.e if I reload the page, the jwt string disappears.
Quick workaround (janky) that I was able to come up is using rx.script by writing my own JS code manipulating document.cookie. But what would be the best way to do this?
Even with the above method, I am not sure how to access the output of JS code in my Python code.
Any help is greatly appreciated!
Even with the above method, I am not sure how to access the output of JS code in my Python code.
For this (janky) method I think I can use rx.call_script