expose rx.get_state() to get instance of state from anywhere
small example sending state info related to a specific token through API
import reflex as rx
from fastapi import Request, Response
class State(rx.State):
foo = "bar"
@rx.page()
def index():
return rx.text(State.router.session.client_token)
app = rx.App()
@app.api.route("/api")
async def get(request: Request):
token = "add_token_here" # copy the one rendered in the page
state = await rx.get_state(token, State)
return Response(state.foo)
this is a bit of a dangerous API, because if the state is modified, then that is essentially thrown away (unless in dev mode).
i think it would be better to expose a wrapper over
app.modify_statewith an async contextmanager.if we definitely want a
get_statethat maybe skips taking a lock or sending an update or something, i think that's okay, but we should wrap it in a StateProxy like a background task so it cannot be modified outside ofasync with state:
I think it could have its use, mostly as a way to get a snapshot of the state at instant t (when the API request arrive for example)
it's a part of this POC: https://github.com/reflex-dev/reflex/pull/2819, stripped down for minimal changes.
I do plan to also wrap / expose modify_state, but it'll be more complex because we need to solve the synchronicity problem between workers (above PR has a solution, but if redis is optional, I'm not sure it's applicable anymore)
rx.get_state should follow the same rules as State.get_state ie => read-only
rx.get_state should follow the same rules as State.get_state ie => read-only
When you do await self.get_state(MyState) inside an event handler, you can modify the state that comes back, it's not read-only
I see.
Will have to brainstorm a bit on this to figure out the ideal way.