hydrate_middleware.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Middleware to hydrate the state."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Optional
  4. from reflex import constants
  5. from reflex.event import Event, get_hydrate_event
  6. from reflex.middleware.middleware import Middleware
  7. from reflex.state import BaseState, StateUpdate
  8. from reflex.utils import format
  9. if TYPE_CHECKING:
  10. from reflex.app import App
  11. class HydrateMiddleware(Middleware):
  12. """Middleware to handle initial app hydration."""
  13. async def preprocess(
  14. self, app: App, state: BaseState, event: Event
  15. ) -> Optional[StateUpdate]:
  16. """Preprocess the event.
  17. Args:
  18. app: The app to apply the middleware to.
  19. state: The client state.
  20. event: The event to preprocess.
  21. Returns:
  22. An optional delta or list of state updates to return.
  23. """
  24. # If this is not the hydrate event, return None
  25. if event.name != get_hydrate_event(state):
  26. return None
  27. # Clear client storage, to respect clearing cookies
  28. state._reset_client_storage()
  29. # Mark state as not hydrated (until on_loads are complete)
  30. setattr(state, constants.CompileVars.IS_HYDRATED, False)
  31. # Get the initial state.
  32. delta = format.format_state(state.dict())
  33. # since a full dict was captured, clean any dirtiness
  34. state._clean()
  35. # Return the state update.
  36. return StateUpdate(delta=delta, events=[])