Skip to content

Store, Actions, and Reducers

The store holds the data your panels show, in one place. Code changes it by dispatching an action, a reducer you write turns the action into the new state, and every view that listens redraws.

Animation: Kael clicks +1 on a counter panel. The click dispatches COUNT_ADDED, the reducer receives a copy of the state and returns it with the count raised from 4 to 5, the store keeps that copy in place of the old state, and both Kael's panel and Mira's panel in the same server redraw to show 5.

A Counter Every Panel Shares

The counter on Your First Panel keeps its count on the view, so each panel counts alone. Here the count lives in the store, one count per server, and every open counter in the server shows it:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card, cascade_reducer, read_slot


@cascade_reducer("COUNT_ADDED")  # (1)!
def add_to_count(action, state):
    counts = state["application"].setdefault("counts", {})
    guild = str(action["payload"]["guild_id"])  # (2)!
    counts[guild] = counts.get(guild, 0) + action["payload"]["amount"]
    return state


class CounterView(StatefulLayoutView):
    subscribed_actions = {"COUNT_ADDED"}  # (3)!

    def state_selector(self, state):
        return read_slot(state, "counts", str(self.guild_id), default=0)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.build_ui()

    def build_ui(self):
        count = read_slot(self.state_store.state, "counts", str(self.guild_id), default=0)
        self.clear_items()
        self.add_item(card(f"Count: **{count}**"))
        self.add_item(
            discord.ui.ActionRow(
                StatefulButton(
                    label="+1",
                    style=discord.ButtonStyle.primary,
                    callback=self.increment,
                    allow_double_click=True,
                )
            )
        )

    async def increment(self, interaction: discord.Interaction):
        await self.dispatch("COUNT_ADDED", {"guild_id": self.guild_id, "amount": 1})  # (4)!
  1. Registers the function as the reducer for every COUNT_ADDED action. It gets a copy of the state, changes it, and returns it. The store keeps what it returns.
  2. Keys are strings: with persistence on, the state is saved as JSON, whose keys are always strings.
  3. The view hears COUNT_ADDED actions, and state_selector() picks the number it shows, so it redraws only when that number changes. Subscribers and Slots covers both.
  4. dispatch() comes with every view and sends the action to the store. The callback redraws nothing itself. The store tells every CounterView that hears the action, this one included, and each runs build_ui() and sends the new panel.

Kael clicks +1. The callback dispatches COUNT_ADDED, the reducer adds 1 to the server's count, and every counter in the server redraws: Kael's, and Mira's beside it. The panel is sent as any view is, with await CounterView(interaction=interaction).send().

The State Store

There is one store in the process. get_store() returns it, and every view holds the same store as self.state_store:

from cascadeui import get_store, read_slot

store = get_store()
count = read_slot(store.state, "counts", "1234", default=0)  # (1)!
  1. store.state is the current state, a dict. Your data lives under store.state["application"], and The State Tree shows the rest.

Actions and Dispatch

An action is a dict that names one change:

Key Holds
type The action's name, a non-empty string such as "COUNT_ADDED"
payload What was passed with it, as given, or {} when nothing was
source The id of the view that dispatched it, or None
timestamp When it was dispatched, as an ISO 8601 string in UTC

A view's dispatch() sets source to the view's id. Code with no view at hand, such as a scheduled task or a command, dispatches on the store:

await get_store().dispatch("COUNT_ADDED", {"guild_id": 1234, "amount": 5})

The payload can be any value, and the reducer gets it as given, 0 and [] included. dispatch() returns the store's state after the action. By then the view that dispatched has redrawn, and the other views that hear the action redraw in the background.

When a Dispatch Goes Wrong

dispatch() raises in three cases:

  • An action type that is not a non-empty string: TypeError, or ValueError for "". A whole action passed as dispatch(action) gets an error naming the fix, dispatch(action["type"], action["payload"]).
  • A dispatch from inside a reducer: RuntimeError (see A Reducer Cannot Dispatch).
  • An exception a middleware raises.

It raises them without logging them, so an error you catch leaves nothing in the log. A reducer, a subscriber, or a hook that raises is different: the store logs it at ERROR with its traceback and dispatch() returns, so the code after it still runs:

# ... in a view's callback
await self.dispatch("GAME_FINISHED", {"winner": winner_id})
await self.exit_children()  # runs even if a view hearing GAME_FINISHED raised

The action-type rule holds wherever a type is taken. @cascade_reducer(), store.on(), subscribe(action_filter=), and a view's subscribed_actions raise when they are given one, so a reducer, hook, or filter no dispatch could reach is never registered.

Built-in Actions

The library dispatches these itself. Built-in Actions lists each one's payload. No reducer can be registered for them, but middleware and event hooks can watch them.

Action Dispatched when
VIEW_CREATED A view is sent, navigated to, or restored after a restart
VIEW_UPDATED A view's record changes: the message it was sent to, its owner or server, or the undo steps a navigation carries
VIEW_DESTROYED A view closes: exit(), a timeout, its message deleted, or a navigation away from it
SESSION_CREATED A view with a session is registered. The first one makes the session
SESSION_UPDATED update_session() writes session data
NAVIGATION_PUSH, NAVIGATION_POP, NAVIGATION_REPLACE push(), pop(), or replace() moves to another view
SCOPED_UPDATE dispatch_scoped() writes scoped state
COMPONENT_INTERACTION A library control's callback finishes: a StatefulButton, a StatefulSelect, or a builder's control, unless it closed the view or moved the panel
MODAL_SUBMITTED A Modal built with view_id= is submitted and its validators pass
PERSISTENT_VIEW_REGISTERED, PERSISTENT_VIEW_UNREGISTERED A persistent panel is sent, or retired
REGISTRY_PRUNED Rows are deleted from the persistent panel registry
APPLICATION_SLOTS_PRUNED Saved slots are removed by a prune or by their expiry
APPLICATION_SLOTS_RELOADED Saved slots another process changed are read back from PostgreSQL
INSPECTOR_PURGED_STALE The DevTools inspector's Purge Stale clears the store's records of past clicks and submissions
UNDO, REDO A view's undo() or redo()
BATCH_COMPLETE A batch closes. It goes to subscribers and hooks only, not through middleware, reducers, or history

One panel's life, as store.history records it:

The actions one CounterView records. Sending it records SESSION_CREATED, VIEW_CREATED, and VIEW_UPDATED. A click on +1 records COUNT_ADDED from the callback and then COMPONENT_INTERACTION from the library. exit() records VIEW_DESTROYED.

Custom Reducers

Data kept per person or per server needs no reducer of its own: scoped state writes through a built-in action. Write a reducer when a change deserves a name: several values that change together, a count many views show, or an event other views react to by name. A reducer keeps its data in a slot, a named place under state["application"].

@cascade_reducer(action_type) registers a function as the reducer for one action type:

  • It is called with (action, state). state is a copy of the store's state, made for this call: change it and return it, and the store keeps what you return.
  • It can be a plain def or an async def.
  • A reducer that returns anything but a dict, a forgotten return most often, is logged at ERROR naming the fix, and the store keeps the state it had.
  • A reducer that raises is logged at ERROR with its traceback. The store keeps the state it had, and the action still reaches its subscribers and hooks.
  • A second reducer for the same type replaces the first and logs a WARNING.

The decorator refuses what could never run: a function that cannot take (action, state) and an action type that is not a string raise TypeError, and "" or a built-in action's name raise ValueError.

One Reducer at a Time

Timeline: a reducer awaits a 2-second database call. A second dispatch sent half a second later waits. Once the first reducer's result is kept, with the count at 6, the second reducer runs, reads 6, and keeps 7.

The store runs one reducer at a time, from reading the state to keeping the result. Two people clicking at once both count: the second dispatch waits for the first reducer, then reads the state it left.

A reducer that awaits slow work, such as a database call, holds up every other dispatch until it returns, and a dispatch kept waiting 30 seconds logs a WARNING naming the action whose reducer it waits for. Do the slow work before dispatching, and pass its result in the payload:

class CounterView(StatefulLayoutView):
    # ... as above

    async def load_total(self, interaction: discord.Interaction):
        total = await fetch_total(self.guild_id)  # your own database call
        await self.dispatch("TOTAL_LOADED", {"guild_id": self.guild_id, "total": total})

A Reducer Cannot Dispatch

A reducer's result replaces the state, so an action dispatched from inside it would be lost. dispatch() there raises RuntimeError, and so does a dispatch from a task the reducer starts while it runs, such as an asyncio.gather() around one. Unless the reducer catches the error, its own change is lost too.

Dispatch the follow-up after the first dispatch() returns, or from an event hook, which runs once the state is kept.

Writes that do not wait for a reducer

Only a dispatch and set_scoped() wait for a reducer running in another task. A write made in place on store.state, such as access_slot(store.state, ...) in seed_initial_state(), lands at once, and a reducer that keeps its result after it replaces it.

Reading the State Later

Each action that changes the state replaces store.state with a new dict instead of changing the old one. A reference you keep across an await goes on reading the state as it was, so read store.state again:

before = store.state
await store.dispatch("COUNT_ADDED", {"guild_id": 1234, "amount": 1})
read_slot(before, "counts", "1234", default=0)       # the count before the dispatch
read_slot(store.state, "counts", "1234", default=0)  # the count now

Inside a reducer, read the state it was given, the copy it returns, not store.state.

Action History

store.history keeps the newest 100 actions and drops the oldest first. Set store.history_limit to keep more or fewer. A batch records each of its actions here, never its BATCH_COMPLETE. The DevTools inspector shows the list on its History tab.

An action type that no reducer handles and nothing hears is logged at WARNING when it is dispatched, No reducer found for action type COUNT_ADED, which catches a misspelled type. One that a hook hears, or a subscriber whose filter names it or who hears every action, is a broadcast and is logged only at DEBUG.