Skip to content

State Management

Ref:

PyTauri implements state management API consistent with Rust Tauri. Reading Tauri's documentation is like reading PyTauri's documentation.

Managing and Accessing State

from dataclasses import dataclass
from typing import Union

from pytauri import App, AppHandle, Manager
from pytauri.webview import WebviewWindow


# ⭐ `Manager` uses `type(state)` as the key to store state,
# so it's best to define a separate newtype to represent the state.
@dataclass
class MyState:
    value: int = 0


def manage_and_access_state(manager: Union[App, AppHandle, WebviewWindow]) -> None:
    state = MyState()

    # ⭐ Store the state
    Manager.manage(manager, state)

    # ⭐ Later, we can access this state elsewhere.
    state1: MyState = Manager.state(manager, MyState)
    state1.value = 42
    assert state1 is state

State injection in Commands

You can inject state into any Command, with any type and any parameter name, as long as you use Annotated[T, State()] as its type annotation.

Note

You must Manager.manage these states before you invoke the command, or the invocation will be rejected.

# pyright: reportRedeclaration=none
# ruff: noqa: ARG001, F811

from typing import Annotated

from pytauri import AppHandle, Commands, State

commands = Commands()


class MyState: ...


@commands.command()
async def command(
    app_handle: AppHandle,
    my_state: Annotated[MyState, State()],  # ⭐
) -> None:
    assert isinstance(my_state, MyState)


@commands.command()
async def command(
    body: int,
    # ⭐ Arbitrary names, arbitrary quantities, and arbitrary types of state injection
    my_state_foo: Annotated[MyState, State()],
    my_state_bar: Annotated[str, State()],
) -> None:
    pass