hydrate_middleware.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 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. # Apply client side storage values to state
  32. for storage_type in (constants.COOKIES, constants.LOCAL_STORAGE):
  33. if storage_type in event.payload:
  34. for key, value in event.payload[storage_type].items():
  35. state_name, _, var_name = key.rpartition(".")
  36. var_state = state.get_substate(state_name.split("."))
  37. setattr(var_state, var_name, value)
  38. # Get the initial state.
  39. delta = format.format_state(state.dict())
  40. # since a full dict was captured, clean any dirtiness
  41. state._clean()
  42. # Get the route for on_load events.
  43. route = event.router_data.get(constants.RouteVar.PATH, "")
  44. # Add the on_load events and set is_hydrated to True.
  45. events = [*app.get_load_events(route), type(state).set_is_hydrated(True)] # type: ignore
  46. events = fix_events(events, event.token, router_data=event.router_data)
  47. # Return the state update.
  48. return StateUpdate(delta=delta, events=events)