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
import { useLiveStateData, useSetLiveStateData, useLiveState} from '@veltdev/react';
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
;
const liveStateDataId = 'uniqueId';
const liveStateData = { 'key': 'value' }; // any type of data
useSetLiveStateData(liveStateDataId, liveStateData)
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)
const liveStateDataId = 'uniqueId';
let data = useLiveStateData(liveStateDataId)
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:
const liveStateDataConfig = {
listenToNewChangesOnly: true // default is false
};
const liveStateData = useLiveStateData(LIVE_STATE_DATA_KEY, liveStateDataConfig)
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:
const [value, setValue] = useLiveState(UNIQUE_ID, INITIAL_VALUE, OPTIONS);
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:
import { useLiveState } from "@veltdev/react";
export function MyReactComponent() {
const [counter, setCounter] = useLiveState < number > ("counter", 0, {
syncDuration: 100,
resetLiveState: true
});
return (
<div>
<button onClick={() => setCounter((counter || 0) - 1)}>-</button>
<span>Counter: {counter}</span>
<button onClick={() => setCounter((counter || 0) + 1)}>+</button>
</div>
);
}
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:
const [counter, setCounter] = useLiveState < number > ("counter", 0, {
syncDuration: 100,
resetLiveState: true,
listenToNewChangesOnly: true // default is false
});
Listen to Server Connection State Changes
You can listen to changes in the server connection state with the useServerConnectionStateChangeHandler()
hook.
const serverConnectionState = useServerConnectionStateChangeHandler();
The server connection state will be an ENUM with the following states:
export enum ServerConnectionState {
ONLINE = 'online',
OFFLINE = 'offline',
PENDING_INIT = 'pendingInit',
PENDING_DATA = 'pendingData',
}
The useLiveState()
hook can also return the server connection state as the third return value.
import { useEffect } from 'react';
import { useLiveState, useServerConnectionStateChangeHandler } from '@veltdev/react';
function YourComponent() {
const serverConnectionState = useServerConnectionStateChangeHandler();
useEffect(() => {
console.log('serverConnectionState', serverConnectionState);
}, [serverConnectionState]);
// Returning serverConnectionState in useLiveState
const [stateValue, setStateValue, serverConnectionStateInLiveState] = useLiveState(STATE_KEY, INITIAL_VALUE);
useEffect(() => {
console.log('stateValue:', stateValue, 'serverConnectionStateInLiveState:', serverConnectionStateInLiveState);
}, [stateValue, serverConnectionStateInLiveState]);
return (
// ... your component code
);
}
Was this page helpful?