Setup
Live State Sync
With Live State Sync
, you can create a shared data object that persists and syncs across all clients live on a given document.
Import useLiveStateData, useSetLiveStateData, and useLiveState hooks
Set or Update a shared live data object
The useSetLiveStateData()
hook can be used to set or update a custom shared data object that will be synced across all clients live on the current document.
Pass in a unique ID and the data object you want to sync. If the object already exists with that ID, then it will be updated.
Input params:
liveStateDataId
:string
;liveStateData
:any
;
The hook will automatically unsubscribe from the subscription when the component dismounts.
Get a shared live data object
The useLiveStateData()
hook can be used to get the live state data object.
Pass in the unique ID that you had used to set the data.
Input params:
liveStateDataId
:string
; (optional)
By default, the useLiveStateData()
subscription will return all changes to the shared live data object including changes that occured when the current client was not subscribed.
If you want to only receive changes starting from when the client subscribed to useLiveStateData()
, you can pass a config object as shown below:
Sync Data Realtime
If you are familiar with React’s useState()
hook, we have a similar hook called useLiveState()
that can be used to sync data realtime for specific state variables in your code.
Hook syntax:
The hook takes in 3 parameters:
UNIQUE_ID
-> unique id in string to be synced across the screensINITIAL_VALUE
-> initial value of the stateOPTIONS
(object)syncDuration
-> debounce duration in milliseconds to sync realtime (optional, default value 50ms)resetLiveState
-> Boolean to reset locatl state value on server side on initiatlize of hook (default:false
)
The hook returns a setter and getter:
value
-> current state value (similar to useState hook)setValue
-> function to be called to set next value (similar to useState hook)
Example:
By default, useLiveState()
will return all changes to the shared live data object including changes that occured when the current client was not subscribed.
If you want to only receive changes starting from when the client subscribed to useLiveState()
, you can pass a config object as shown below:
Listen to Server Connection State Changes
You can listen to changes in the server connection state with the useServerConnectionStateChangeHandler()
hook.
The server connection state will be an ENUM with the following states:
The useLiveState()
hook can also return the server connection state as the third return value.
Was this page helpful?