Fields, derived values and actions
What a store class is made of, and what happens when its methods change it.
janelkit-store Shared application data: stores with actions, controlled writes and change tracking, one instance per application, and persistence. pip install janelkit-storeFields
Each annotated attribute of the class is a reactive field with its default value, copied for each instance, so two instances never share a list. Fields are read and written as ordinary attributes, without .value, in Python and in the template. Nested data, such as a card inside a list, belongs to the field that contains it.
An attribute whose name starts with an underscore is internal: it is not reactive, not recorded and not saved. field(default, bind=False, persist=True) gives a field options; the next pages explain them.
from janelkit_store import field, store
@store
class Session:
user: str | None = None
recent: list[str] = []
theme: str = field("light", persist=False)
_cache: dict = {} # internal: not reactive, not recorded, not savedCopyDerived values
@computed, from the core, on a method gives a cached value that is read without .value and is not assigned: cart.total. It is recalculated only when a field it read changes, and only when someone reads it.
Actions
Every method is an action, except setup, teardown and the __dunder__ methods. An action groups its changes in a batch, so what depends on them is recalculated once, and records them as one Mutation. An action called inside another action of the same store becomes part of it. In an async method, what changes after an await still belongs to that action. What an action creates, such as an effect, a timeout or a task, belongs to the store and lives as long as it does.
from janelkit import background
from janelkit_store import store
@store
class Library:
books: list[dict] = []
loading: bool = False
async def load(self):
self.loading = True
self.books = await background(read_catalog) # still the action "load"
self.loading = FalseCopysetup and teardown
setup(self), or setup(self, key) for a store with keys, runs when an instance is created, and teardown(self) when it is released. They are not actions: what they change is not recorded. A store does not define __init__: the initial values are the class defaults, and setup prepares the rest. A store can use another one with use(Other) inside a method or in setup.
Common mistakes
- Do not define __init__ in a store; it is refused. Put preparation in setup.
- Do not keep a reference to a value read from another store inside a field; read it when you need it, through use().
English documentation based on the JanelKit source. For additional details, browse the source docs ↗.