Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 4 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions reflex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@
"ComponentState",
"State",
],
"istate": ["get_state"],
"style": ["Style", "toggle_color_mode"],
"utils.imports": ["ImportVar"],
"utils.serializers": ["serializer"],
Expand Down
1 change: 1 addition & 0 deletions reflex/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ from .event import stop_propagation as stop_propagation
from .event import upload_files as upload_files
from .event import window_alert as window_alert
from .experimental import _x as _x
from .istate import get_state as get_state
from .middleware import Middleware as Middleware
from .middleware import middleware as middleware
from .model import Model as Model
Expand Down
3 changes: 3 additions & 0 deletions reflex/istate/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""This module will provide interfaces for the state."""

from .wrappers import get_state
25 changes: 25 additions & 0 deletions reflex/istate/wrappers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Wrappers for the state manager."""

from typing import Any

from reflex.state import _split_substate_key, _substate_key, get_state_manager


async def get_state(token, state_cls: Any | None = None):
"""Get the instance of a state for a token.

Args:
token: The token for the state.
state_cls: The class of the state.

Returns:
The state instance.
"""
mng = get_state_manager()
if state_cls is not None:
root_state = await mng.get_state(_substate_key(token, state_cls))
else:
root_state = await mng.get_state(token)
_, state_path = _split_substate_key(token)
state_cls = root_state.get_class_substate(tuple(state_path.split(".")))
return await root_state.get_state(state_cls)
Loading