Changing data: actions
load reads data. To change it (save a form, place an order, sign in) use an action: a
function decorated with @pz.action, called from any button. It is Pyzed’s version of Next.js’
server actions with useActionState.
# app/(shop)/products/[id]/page.pyimport pyzed as pzfrom pyzed import ui
import apifrom state import cart
@pz.actionasync def add_to_cart(product): await api.place_order([product.id]) # off the UI thread cart.add(product.id) # the global state: the header's badge updates
def page(data): return ui.button("Adding…" if add_to_cart.pending else "Add to cart", lambda: add_to_cart(data), loading=add_to_cart.pending)
What happens when you call it
Section titled “What happens when you call it”pendingbecomesTrue, so the button can say “Adding…” or show a spinner.- The function runs off the UI thread:
async defon Pyzed’s loop, a plaindefin a worker thread. The window keeps answering. - When it ends,
resultholds what it returned, orerrorthe exception it raised. - The current page’s
loadruns again (refresh=True), keeping the old data on screen meanwhile, so what the page shows matches the server.
An action is a pz.Store: the components that read pending,
result or error draw again by themselves when they change.
| Attribute or call | What it is |
|---|---|
pending |
True while it runs |
result |
what the last call returned |
error |
the exception of the last call, or None |
calls |
how many times it was called |
action(...) |
starts it and returns a Future |
action.run(...) |
starts it and waits (tests and scripts) |
action.reset() |
clears result and error |
Options
Section titled “Options”@pz.action(refresh=False, # don't reload the current page afterwards invalidate=["/products", "/products/[id]"], # mark other pages' data as old on_done=lambda result: pz.use_router().push("/orders"), on_error=lambda error: pz.notify("Couldn't save", str(error)))async def save(form): ...on_done(result) and on_error(error) run on the UI thread, so they can navigate, change a
component’s state or show a notification. Without on_error, the error is printed in the
terminal and kept in error for the page to show.
invalidate takes addresses ("/products/3") or patterns ("/products/[id]", every product):
like Next.js’ revalidatePath, their data loads again the next time they show.
Showing errors
Section titled “Showing errors”def page(data): return pz.column([ ui.button("Save", lambda: save(data), loading=save.pending), ui.label(str(save.error), color="danger") if save.error else None, ])A form that signs in
Section titled “A form that signs in”The login page of the example keeps the name in the component’s state, signs in with an action and goes where the middleware stopped the user:
def signed_in(next_href): pz.use_router().replace(next_href or "/account")
@pz.action(refresh=False, on_done=signed_in)async def sign_in(name, next_href): session.user = await api.sign_in(name) return next_href
class Page(pz.Component): query: dict = {} name = pz.state("Ada")
def render(self): return pz.column([ ui.input(self.name, on_input=lambda v: setattr(self, "name", v)), ui.button("Sign in", lambda: sign_in(self.name, self.query.get("next")), loading=sign_in.pending), ])Good to know
Section titled “Good to know”- An action defined at the top of a file is one for the whole app: two product pages share
its
pending. For one per item, keep the state in the item’s component (pz.state) or make the action inside a component’ssetup. - Keep the network and the database in
api.pyand call them from actions; the page only decides what to show. - In tests,
add_to_cart.run(product)waits for the result and raises its error.