hydrate_middleware.py 1.5 KB

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