hydrate_middleware.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Middleware to hydrate the state."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Optional
  4. from pynecone import constants
  5. from pynecone.event import Event, fix_events, get_hydrate_event
  6. from pynecone.middleware.middleware import Middleware
  7. from pynecone.state import State, StateUpdate
  8. from pynecone.utils import format
  9. if TYPE_CHECKING:
  10. from pynecone.app import App
  11. State.add_var(constants.IS_HYDRATED, type_=bool, default_value=False)
  12. class HydrateMiddleware(Middleware):
  13. """Middleware to handle initial app hydration."""
  14. async def preprocess(
  15. self, app: App, state: State, event: Event
  16. ) -> Optional[StateUpdate]:
  17. """Preprocess the event.
  18. Args:
  19. app: The app to apply the middleware to.
  20. state: The client state.
  21. event: The event to preprocess.
  22. Returns:
  23. An optional delta or list of state updates to return.
  24. """
  25. # If this is not the hydrate event, return None
  26. if event.name != get_hydrate_event(state):
  27. return None
  28. # Get the initial state.
  29. delta = format.format_state({state.get_name(): state.dict()})
  30. # Get the route for on_load events.
  31. route = event.router_data.get(constants.RouteVar.PATH, "")
  32. # Add the on_load events and set is_hydrated to True.
  33. events = [*app.get_load_events(route), type(state).set_is_hydrated(True)] # type: ignore
  34. events = fix_events(events, event.token)
  35. # Return the state update.
  36. return StateUpdate(delta=delta, events=events)