hydrate_middleware.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, fix_events, get_hydrate_event
  6. from reflex.middleware.middleware import Middleware
  7. from reflex.state import State, StateUpdate
  8. from reflex.utils import format
  9. if TYPE_CHECKING:
  10. from reflex.app import App
  11. State.add_var(constants.CompileVars.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. # Clear client storage, to respect clearing cookies
  29. state._reset_client_storage()
  30. # Mark state as not hydrated (until on_loads are complete)
  31. setattr(state, constants.CompileVars.IS_HYDRATED, False)
  32. # Apply client side storage values to state
  33. for storage_type in (constants.COOKIES, constants.LOCAL_STORAGE):
  34. if storage_type in event.payload:
  35. for key, value in event.payload[storage_type].items():
  36. state_name, _, var_name = key.rpartition(".")
  37. var_state = state.get_substate(state_name.split("."))
  38. setattr(var_state, var_name, value)
  39. # Get the initial state.
  40. delta = format.format_state({state.get_name(): state.dict()})
  41. # since a full dict was captured, clean any dirtiness
  42. state._clean()
  43. # Get the route for on_load events.
  44. route = event.router_data.get(constants.RouteVar.PATH, "")
  45. # Add the on_load events and set is_hydrated to True.
  46. events = [*app.get_load_events(route), type(state).set_is_hydrated(True)] # type: ignore
  47. events = fix_events(events, event.token, router_data=event.router_data)
  48. # Return the state update.
  49. return StateUpdate(delta=delta, events=events)