Add Var.dispatch_value for speculative frontend updates

MA
7d ago
+553-8

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

Part 4 of 4 of #7302. Stack: 1 field descriptors (#7312) → 2 state locks (#7313) → 3 core state in reflex-base (#7314) → 4 dispatch_value. Based on #7314.

Description

Adds Var.dispatch_value, which shows a value for a state var in the browser right away, before the event reaches the backend:

rx.button("Work", loading=State.loading, on_click=[State.loading.dispatch_value(True), State.work])
  • It returns a frontend-only _dispatch_value event. state.js applies it directly to the state's reducer through eventLoop.dispatch, which EventLoopProvider publishes.
  • The value stays until the backend sends a value for the var. For an inherited var, it targets the state that declares the var.
  • Only state fields sent to the client can be dispatched:
    • Any other var, such as State.x + 1, raises TypeError.
    • So does a computed var, because only the backend computes it.
    • A backend field has no var on its class, so it has no dispatch_value at all (AttributeError).
  • A value whose type doesn't match the var's type is logged as an error, the same way a backend write of that value is. A var value is checked against its declared type.
  • If the target state isn't mounted, it logs a console warning. After a fatal frontend/backend state mismatch, the dispatched value is dropped along with the rest of the event queue.
  • Docs: new "Speculative Updates" section in docs/events/special_events.md. It covers:
    • handlers that raise
    • values from older events replacing a newer dispatched value
    • computed vars
  • Tests:
    • unit tests
    • frontend event queue tests, including offline ordering, the state-mismatch drop and the missing-state warning
    • a Playwright test checking that a value only the frontend sets appears, then gets replaced by the backend's

New Feature Submission:

  • Does your submission pass the tests?
  • Have you linted your code locally prior to submission?

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

šŸ¤– Generated with Claude Code

https://claude.ai/code/session_0145YmAVjKSJhdUFDcBP4FB9


Generated by Claude Code