reflex icon indicating copy to clipboard operation
reflex copied to clipboard

expose rx.get_state() to get instance of state from anywhere

Open Lendemor opened this issue 1 year ago β€’ 3 comments

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)

Lendemor avatar Sep 19 '24 22:09 Lendemor

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_state with an async contextmanager.

if we definitely want a get_state that 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 of async 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

Lendemor avatar Sep 20 '24 01:09 Lendemor

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

masenf avatar Sep 20 '24 16:09 masenf

I see.

Will have to brainstorm a bit on this to figure out the ideal way.

Lendemor avatar Sep 20 '24 20:09 Lendemor