SyncStateMixin allows you to sync state data from the server to the client when hydrating components. This is useful for passing server-side data to the client without additional network requests.
SyncStateMixin
A mixin onState that syncs state data from the server to the client.
Signature
The type of the component this state is associated with.
The type of the state data to sync. Can be any JSON-serializable type.
Methods
getState()
Called on the server after the initial build to retrieve the state data of this component.Returns: The state data to sync to the client.
updateState()
Called on the client during
initState() to receive the synced state from the server.The state data received from the server.
Usage
Syncing Complex Data
You can sync any JSON-serializable data structure:@sync Annotation
The@sync annotation is a code generation marker that works with the Jaspr builder to automatically implement SyncStateMixin for you.
Usage with @sync
Instead of manually implementinggetState() and updateState(), you can use the @sync annotation:
- A mixin named
{ClassName}SyncMixin - Automatic implementation of
getState()andupdateState() - Serialization/deserialization logic for all
@syncfields
When using
@sync, you must:- Run
dart run build_runner buildto generate the code - Include the
partdirective for the generated file - Apply the generated mixin to your state class
Initialization Order
Itβs important to understand whenupdateState() is called:
On initialization,
updateState() is called as part of the super.initState() call. It is recommended to start with the super.initState() call in your custom initState() implementation. However, if you need to do some work before updateState() is called, you can invoke super.initState() later in your implementation.Combining with PreloadStateMixin
You can use both mixins together to preload data on the server and sync it to the client:How It Works
- Server-side: After the component builds,
getState()is called and the data is serialized to JSON - HTML Markup: The serialized data is embedded as an HTML comment in the rendered output
- Client-side: During hydration, the comment is parsed and
updateState()is called with the deserialized data - Cleanup: The HTML comment is removed from the DOM
See Also
- PreloadStateMixin - Preload async data on the server
- @client Components - Passing data through client components
- @encoder/@decoder - Custom serialization for classes