From 1124067c128def268f64b666f13ab7dd4106ba95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Brand=C3=A9ho?= Date: Sun, 8 Jan 2023 22:48:09 +0100 Subject: [PATCH] Add router data to state (#228) --- pynecone/.templates/web/utils/state.js | 3 +++ pynecone/app.py | 2 ++ pynecone/event.py | 3 +++ pynecone/state.py | 12 ++++++++++++ tests/test_state.py | 1 + 5 files changed, 21 insertions(+) diff --git a/pynecone/.templates/web/utils/state.js b/pynecone/.templates/web/utils/state.js index b0612df83..b81e5e674 100644 --- a/pynecone/.templates/web/utils/state.js +++ b/pynecone/.templates/web/utils/state.js @@ -70,6 +70,9 @@ export const applyDelta = (state, delta) => { */ export const applyEvent = async (event, router, socket) => { // Handle special events + + event.router_data = (({ pathname, query }) => ({ pathname, query }))(router); + if (event.name == "_redirect") { router.push(event.payload.path); return; diff --git a/pynecone/app.py b/pynecone/app.py index eac25b905..70dfd2719 100644 --- a/pynecone/app.py +++ b/pynecone/app.py @@ -297,6 +297,8 @@ async def process(app: App, event: Event) -> StateUpdate: # Get the state for the session. state = app.state_manager.get_state(event.token) + state.router_data = event.router_data + # Preprocess the event. pre = app.preprocess(state, event) if pre is not None: diff --git a/pynecone/event.py b/pynecone/event.py index 08f5983ff..986081528 100644 --- a/pynecone/event.py +++ b/pynecone/event.py @@ -18,6 +18,9 @@ class Event(Base): # The event name. name: str + # The routing data where event occured + router_data: Dict[str, Any] = {} + # The event payload. payload: Dict[str, Any] = {} diff --git a/pynecone/state.py b/pynecone/state.py index 0c1270865..9d2eaa329 100644 --- a/pynecone/state.py +++ b/pynecone/state.py @@ -45,6 +45,9 @@ class State(Base, ABC): # The set of dirty substates. dirty_substates: Set[str] = set() + # The routing path that triggered the state + router_data: Dict[str, Any] = {} + def __init__(self, *args, **kwargs): """Initialize the state. @@ -89,6 +92,7 @@ class State(Base, ABC): "substates", "dirty_vars", "dirty_substates", + "router_data", } cls.base_vars = { f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls) @@ -257,6 +261,14 @@ class State(Base, ABC): field.required = False field.default = default_value + def get_current_page(cls) -> str: + """Obtain the path of current page from the router data. + + Returns: + The current page. + """ + return cls.router_data["pathname"] + def __getattribute__(self, name: str) -> Any: """Get the state var. diff --git a/tests/test_state.py b/tests/test_state.py index ad60322ee..ec7394a99 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -153,6 +153,7 @@ def test_base_class_vars(test_state): "substates", "dirty_vars", "dirty_substates", + "router_data", ): continue prop = getattr(cls, field)