Optimistic Updates & Background Tasks

New decorators for instant UI feedback and non-blocking handlers.

Shopping Cart

@optimistic JIT compute

Subtotal, tax, and total are derived in get_context_data() (JIT pattern). "Add Item" uses @optimistic for instant client-side feedback before the server responds.

Item Price Qty Line Total
Wireless Keyboard $79.99 $79.99
USB-C Hub $49.99 $49.99
Monitor Stand $34.99 $34.99

Order Summary

Items 4
Subtotal $214.96
Tax (8%) $17.20

Total $232.16

Actions

@optimistic @background

"Add Item" uses @optimistic for instant UI feedback. "Check Inventory" uses @background for non-blocking async.

Decorator Reference

views.pypython
from djust.decorators import optimistic, background, event_handler

class CartView(LiveView):
    def get_context_data(self, **kwargs):
        # JIT pattern: compute derived values at render time
        subtotal = sum(i["price"] * i["qty"] for i in self.items)
        return {"subtotal": subtotal, "tax": round(subtotal * 0.08, 2)}

    @event_handler()
    @optimistic        # Instant client-side feedback before server confirms
    def add_item(self, **kwargs):
        self.items.append({"name": "New", "price": 19.99, "qty": 1})

    @event_handler()
    @background        # Runs without blocking — UI stays responsive
    def check_inventory(self, **kwargs):
        time.sleep(2)  # Simulate slow API call
        self.inventory_status = "All items in stock!"