> ## Documentation Index
> Fetch the complete documentation index at: https://velt.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Setup

# Getter and Setter Methods

### Set Live Data

The Live State Sync feature allows you to set and update shared data that syncs in real-time across all connected clients.

**Params**

* `liveStateDataId` (`string`, required): A unique string ID to identify the data
* `liveStateData` (`any serializable type`, required): The data to sync (objects, arrays, strings, numbers)
* `setLiveStateDataConfig` (`object`, optional): Configuration object
  * `merge` (`boolean`): Whether to merge the data with existing data (default: `false`)

<Info>Live State data persists indefinitely until manually removed - there is no automatic cleanup.</Info>

<Tabs>
  <Tab title="React / Next.js">
    ```jsx theme={null}
    const liveStateDataId = 'uniqueId'; // A unique string identifier for the data
    const liveStateData = { 'key': 'value' }; // The data to be synced (can be any serializable type)
    const config = { merge: true };

    // Using Hooks
    useSetLiveStateData(liveStateDataId, liveStateData, config);

    // Using API
    const liveStateSyncElement = useLiveStateSyncUtils();
    liveStateSyncElement.setLiveStateData(liveStateDataId, liveStateData, config);
    ```
  </Tab>

  <Tab title="Other Frameworks">
    ```jsx theme={null}
    const liveStateDataId = 'uniqueId';
    const liveStateData = { 'key': 'value' }; // any type of data
    const config = { merge: true };

    const liveStateSyncElement = Velt.getLiveStateSyncElement();
    liveStateSyncElement.setLiveStateData(liveStateDataId, liveStateData, config);
    ```
  </Tab>
</Tabs>

### Get Live Data

Get live state data by providing the unique ID used when setting the data.

**Params**

* `liveStateDataId` (`string`, required) - A unique string ID to identify the data to retrieve
* `liveStateDataConfig` (`object`, optional) - Configuration object for controlling data retrieval behavior
  * `listenToNewChangesOnly` (`boolean`, optional) - Whether to only receive new changes from when the client subscribed (default: `false`)

<Tabs>
  <Tab title="React / Next.js">
    ```jsx theme={null}
    const liveStateDataConfig = {
    	listenToNewChangesOnly: true // default is false
    };
    const liveStateDataId = 'uniqueId';

    // Using Hooks
    const liveStateData = useLiveStateData(liveStateDataId, liveStateDataConfig);

    // Using API
    const liveStateSyncElement = useLiveStateSyncUtils();
    let subscription = liveStateSyncElement.getLiveStateData(liveStateDataId, liveStateDataConfig).subscribe((data) => {
    		// your logic here...
    });
    ```

    If using API, you can unsubscribe from the subscription after you are done:

    ```jsx theme={null}
    subscription?.unsubscribe()
    ```
  </Tab>

  <Tab title="Other Frameworks">
    ```jsx theme={null}
    const liveStateDataConfig = {
    	listenToNewChangesOnly: true // default is false
    };
    const liveStateDataId = 'uniqueId';

    const liveStateSyncElement = Velt.getLiveStateSyncElement();
    let subscription = liveStateSyncElement.getLiveStateData(liveStateDataId, liveStateDataConfig).subscribe((data) => {
    		// your logic here...
    });
    ```

    To unsubscribe from the subscription:

    ```jsx theme={null}
    subscription?.unsubscribe()
    ```
  </Tab>
</Tabs>

### Fetch Live Data

Fetch live state data as a Promise when you need to retrieve the current state once, rather than subscribing to ongoing changes. This is useful for initialization, conditional logic, or one-time data retrieval.

**When to use `fetchLiveStateData()` vs `getLiveStateData()`:**

* **Use `fetchLiveStateData()`** (Promise): When you need the current value once
* **Use `getLiveStateData()`** (Observable): When you want to reactively update to changes

**Params**

* `request` (`FetchLiveStateDataRequest`, optional): Configuration object
  * `liveStateDataId` (`string`, optional): Unique identifier for specific data. If not provided, returns all live state data.

**Returns**

* `Promise<T>`: Promise resolving to the live state data. Supports generic type for type safety.

**Common Use Cases:**

* Initializing state on component mount
* Checking current state before performing an action
* Loading data for server-side rendering
* One-time data retrieval without needing updates

<Tabs>
  <Tab title="React / Next.js">
    ```jsx theme={null}
    // Using Hooks
    const liveStateSyncElement = useLiveStateSyncUtils();

    /// To get all the data
    const data = await liveStateSyncElement.fetchLiveStateData();

    /// To get data for specific liveStateDataId
    const specificData = await liveStateSyncElement.fetchLiveStateData({
        liveStateDataId: "LIVE_STATE_DATA_ID"
    });

    // Using API methods
    const liveStateSyncElement = client.getLiveStateSyncElement();

    /// To get all the data
    const data = await liveStateSyncElement.fetchLiveStateData();

    /// To get data for specific liveStateDataId
    const specificData = await liveStateSyncElement.fetchLiveStateData({
        liveStateDataId: "LIVE_STATE_DATA_ID"
    });
    ```
  </Tab>

  <Tab title="Other Frameworks">
    ```jsx theme={null}
    const liveStateSyncElement = Velt.getLiveStateSyncElement();

    // To get all the data
    const data = await liveStateSyncElement.fetchLiveStateData();

    // To get data for specific liveStateDataId
    const specificData = await liveStateSyncElement.fetchLiveStateData({
        liveStateDataId: "LIVE_STATE_DATA_ID"
    });
    ```
  </Tab>
</Tabs>

### Alternative: useLiveState()

The `useLiveState()` hook provides a familiar React's `useState()` like API while automatically syncing state changes across all connected clients in real-time.

The hook accepts the following parameters:

* `id` (string, required): Unique identifier for syncing this state across clients
* `initialValue` (any, required): Initial state value
* `options` (object, optional): Configuration object with the following properties:
  * `syncDuration` (number, optional): Debounce delay in milliseconds before syncing. Defaults to 50ms.
  * `resetLiveState` (boolean, optional): Whether to reset server state when the hook initializes. Defaults to false.
  * `listenToNewChangesOnly` (boolean, optional): When true, only receives changes that occur after subscribing and discards historical changes. Defaults to false.

**Returns**

* `[value, setValue, connectionState]`
  * `value`: Current value of the data you set
  * `setValue`: Function to update the data
  * `connectionState`: Current server connection status

<Tabs>
  <Tab title="React / Next.js">
    ```jsx theme={null}
    import { useLiveState } from "@veltdev/react";

    export function MyReactComponent() {
      const [counter, setCounter, serverConnectionStateInLiveState] = useLiveState<number> ("counter", 0, {
        syncDuration: 100,
        resetLiveState: true,
        listenToNewChangesOnly: true // receive only new changes from when the client subscribed
      });

      useEffect(() => {
        console.log('serverConnectionStateInLiveState:', serverConnectionStateInLiveState);
      }, [serverConnectionStateInLiveState]);

      return (
        <div>
          <button onClick={() => setCounter((counter || 0) - 1)}>-</button>
          <span>Counter: {counter}</span>
          <button onClick={() => setCounter((counter || 0) + 1)}>+</button>
        </div>
      );
    }
    ```
  </Tab>
</Tabs>

# Server Connection State

The server connection state indicates the current status of the connection to Velt's servers. The possible states are:

```jsx theme={null}
enum ServerConnectionState {
  ONLINE = 'online', // Connected to Velt's servers
  OFFLINE = 'offline', // Not connected to Velt's servers
  PENDING_INIT = 'pendingInit', // Pending SDK Initialization
  PENDING_DATA = 'pendingData', // Pending receiving data from server
}
```

<Tabs>
  <Tab title="React / Next.js">
    ```jsx theme={null}
    // Using Hooks
    const serverConnectionState = useServerConnectionStateChangeHandler();

    useEffect(() => {
      console.log('serverConnectionState', serverConnectionState);
    }, [serverConnectionState]);

    // Using API
    const liveStateSyncElement = useLiveStateSyncUtils();
    let subscription = liveStateSyncElement.onServerConnectionStateChange().subscribe((data) => {
      console.log('server connection state change: ', data);
    });
    ```

    If using API, you can unsubscribe from the subscription after you are done:

    ```jsx theme={null}
    subscription?.unsubscribe()
    ```
  </Tab>

  <Tab title="Other Frameworks">
    ```jsx theme={null}
    const liveStateSyncElement = Velt.getLiveStateSyncElement();
    let subscription = liveStateSyncElement.onServerConnectionStateChange().subscribe((data) => {
      console.log('server connection state change: ', data);
    });
    ```

    To unsubscribe from the subscription:

    ```jsx theme={null}
    subscription?.unsubscribe()
    ```
  </Tab>
</Tabs>

# Best Practices

* Keep your state data structures simple and flat when possible
* Use meaningful IDs that reflect the purpose of the data
* If using APIs, clean up subscriptions when components unmount
* Consider network latency when setting `syncDuration`
* Sync only what you need, not the entire state
* Use `listenToNewChangesOnly` when appropriate
