Skip to content

Storage

Key/value persistence backed by the platform-native store (NSUserDefaults on iOS, SharedPreferences on Android, a local JSON file in desktop tests). All operations are coroutines so they don't block the framework loop.

Cross-platform key/value persistence (AsyncStorage).

Mirrors React Native's AsyncStorage API but with native async coroutines and a JSON convenience layer. Values are persisted using the platform-appropriate key/value store:

  • iOS: NSUserDefaults (standard user defaults).
  • Android: SharedPreferences (file "pn_async_storage").
  • Desktop / tests: an in-memory dict optionally backed by a JSON file under FileSystem.app_dir for inter-run persistence during local development.

All operations are coroutines so they don't block the framework loop; the underlying native calls are dispatched via :func:asyncio.to_thread.

Example
import pythonnative as pn


async def remember_user(user):
    await pn.AsyncStorage.set_json("current_user", user.to_dict())


async def restore_session():
    user_dict = await pn.AsyncStorage.get_json("current_user")
    if user_dict is None:
        return None
    return User.from_dict(user_dict)

Classes:

Name Description
AsyncStorage

Async key/value persistence layered on platform-native stores.

Functions:

Name Description
use_persisted_state

Persisted use_state variant.

AsyncStorage

Async key/value persistence layered on platform-native stores.

Every method is a coroutine that returns when the underlying native operation completes. Strings round-trip directly via get / set; richer values can use get_json / set_json which add a JSON encode/decode step.

Methods:

Name Description
get

Return the string stored at key, or None if missing.

set

Persist value under key.

delete

Remove the entry at key if present (no-op otherwise).

all_keys

Return every persisted key (order is platform-dependent).

clear

Remove every entry written through AsyncStorage.

get_json

Return the JSON-decoded value stored at key, or None.

set_json

JSON-encode value and persist it under key.

get async staticmethod

get(key: str) -> Optional[str]

Return the string stored at key, or None if missing.

set async staticmethod

set(key: str, value: str) -> None

Persist value under key.

value must be a str. For non-string values, use set_json.

delete async staticmethod

delete(key: str) -> None

Remove the entry at key if present (no-op otherwise).

all_keys async staticmethod

all_keys() -> List[str]

Return every persisted key (order is platform-dependent).

clear async staticmethod

clear() -> None

Remove every entry written through AsyncStorage.

get_json async staticmethod

get_json(key: str) -> Any

Return the JSON-decoded value stored at key, or None.

If the stored value isn't valid JSON, returns None rather than raising — assume the entry was written by another process or an older version of the app.

set_json async staticmethod

set_json(key: str, value: Any) -> None

JSON-encode value and persist it under key.

use_persisted_state

use_persisted_state(key: str, initial: T) -> Tuple[T, Callable[[Any], None]]

Persisted use_state variant.

Backed by AsyncStorage: behaves like use_state but loads the prior value (if any) on mount and persists every subsequent update. Until the load completes the value is initial — the same fallback React Native users get with AsyncStorage.getItem.

The setter accepts either a value or a current -> new callable, matching use_state. Writes are fire-and-forget; failures are silently absorbed (storage is best-effort by design).

Parameters:

Name Type Description Default
key str

Storage key. Pass a stable, namespaced string (e.g. "settings.theme").

required
initial T

Value used before the first load completes.

required

Returns:

Type Description
T

(value, setter) — same shape as

Callable[[Any], None]
Example
import pythonnative as pn


@pn.component
def ThemeToggle():
    theme, set_theme = pn.use_persisted_state("settings.theme", "light")
    return pn.Button(
        f"Theme: {theme}",
        on_click=lambda: set_theme("dark" if theme == "light" else "light"),
    )

Patterns

  • Token / session storage: write strings with set and read with get.
  • Complex values: use set_json / get_json for dicts, lists, and primitives.
  • Component state that survives restarts: reach for use_persisted_state instead of manually wiring an effect to AsyncStorage.

Next steps