#### React
```
import type { LiveMap, PathObject } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const AliceScore = () => {
const { value, object } = useObject((obj: PathObject>) => obj.get('scores').get('alice'));
return ;
};
```
## Install
The `@ably/pubsub-device` package includes the `useObject` hook in its `@ably/pubsub-device/liveobjects/react` entry point. You don't need to install any additional packages.
### Shell
```
npm install @ably/pubsub-device
```
> **Note**
>
> `useObject` requires React 18 or above. The other Pub/Sub React Hooks support React 16.8 or above.
## Authenticate
Client code that runs in a browser authenticates with [token authentication](https://ably.com/docs/auth/token.md), which keeps your API key on your server. The examples on this page fetch tokens from an `/auth` endpoint on your server.
To read objects with `useObject`, the token needs the `object-subscribe` [capability](https://ably.com/docs/auth/capabilities.md). To update objects, it also needs the `object-publish` capability.
## Set up the providers
Create a client with the `LiveObjects` plugin and pass it to a [`PubSubClientProvider`](https://ably.com/docs/getting-started/react-hooks.md#ably-provider). Then wrap the components that use LiveObjects in a `ChannelProvider` that sets the LiveObjects [channel modes](https://ably.com/docs/channels/options.md#modes):
* `OBJECT_SUBSCRIBE` is required to read objects on the channel.
* `OBJECT_PUBLISH` is required to update objects on the channel.
### React
```
import { createClient } from '@ably/pubsub-device';
import { LiveObjects } from '@ably/pubsub-device/liveobjects';
import { ChannelProvider, PubSubClientProvider } from '@ably/pubsub-device/react';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root')!;
const root = createRoot(container);
const pubsubDeviceClient = createClient({
authUrl: '/auth',
plugins: { LiveObjects },
});
root.render(
);
```
> **Note**
>
> When you provide an explicit `modes` property for a channel, you override the set of [default modes](https://ably.com/docs/channels/options.md#modes) used for that channel. If you also use the channel with other hooks, such as `useChannel` or `usePresence`, include the modes those features need.
## Subscribe to the channel object
Call `useObject` with no selector to subscribe to the whole channel object. The examples on this page use a channel object with the following shape, which they pass to the hook as a [type](#typing):
### React
```
import type { LiveCounter, LiveMap } from '@ably/pubsub-device/liveobjects';
type Game = {
title: string;
scores: LiveMap<{
alice: LiveCounter;
bob: LiveCounter;
}>;
};
```
The hook returns `value`, a plain-data snapshot of the object, and `object`, the [PathObject](https://ably.com/docs/liveobjects/concepts/path-object.md) for it. `value` is the result of calling [`compact()`](https://ably.com/docs/liveobjects/concepts/path-object.md#get-a-compact-object) on the object, so a `LiveMap` becomes a plain JavaScript object and a `LiveCounter` becomes a number.
`object` is `undefined` until the channel attaches and the channel object completes its initial synchronization, so check it and render a loading state until then. It is also `undefined` if the channel object can't be resolved, as described in [Handle loading and errors](#loading-errors):
### React
```
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const Scoreboard = () => {
const { value, object } = useObject();
if (!object) {
return Loading...
;
}
return (
<>
{value?.title}
Alice: {value?.scores?.alice ?? 0}
Bob: {value?.scores?.bob ?? 0}
>
);
};
```
The component re-renders whenever the object, or any object nested within it, changes. The hook subscribes to a path rather than to a specific object instance, so it stays up to date when an object at that path is [replaced](https://ably.com/docs/liveobjects/concepts/path-object.md#subscribe).
Two properties of `value` are worth knowing:
* Its identity changes only when the subscribed data changes, so it is safe to use in the dependency arrays of hooks such as `useEffect` and `useMemo`.
* It is a copy. The same data read by two different `useObject` calls produces two snapshots that are not reference-equal. Compare fields rather than snapshots.
## Subscribe to a nested object
Pass a selector function to subscribe to an object nested within the channel object. The selector receives the channel object as a `PathObject` and navigates to a descendant using `get()` or `at()`. The hook subscribes to the path the selector returns, and `value` and `object` refer to that path:
### React
```
import type { LiveMap, PathObject } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const BobScore = () => {
const { value } = useObject((obj: PathObject>) => obj.get('scores').get('bob'));
return Bob: {value ?? 0}
;
};
```
The component re-renders only when the data at that path changes. Select the narrowest path that a component renders to avoid unnecessary re-renders.
The selector must only navigate. Don't read values or update objects in it. The hook calls the selector on every render, and keeps its subscription for as long as the selector returns the same path.
## Update objects
Use the `object` returned by the hook to update objects. It is a [PathObject](https://ably.com/docs/liveobjects/concepts/path-object.md), so it has the same methods for [updating data](https://ably.com/docs/liveobjects/concepts/path-object.md#update), such as `set()` and `remove()` on a `LiveMap`, `increment()` and `decrement()` on a `LiveCounter`, and [`batch()`](https://ably.com/docs/liveobjects/batch.md) to apply several updates together.
`object` is `undefined` until the channel object has synchronized, or if it [can't be resolved](#loading-errors), so check it before you call a method on it:
### React
```
import { LiveCounter, LiveMap } from '@ably/pubsub-device/liveobjects';
import { useObject } from '@ably/pubsub-device/liveobjects/react';
const NewGame = () => {
const { object } = useObject();
const startGame = () =>
object?.batch((ctx) => {
ctx.set('title', 'New game');
ctx.set('scores', LiveMap.create({ alice: LiveCounter.create(0), bob: LiveCounter.create(0) }));
});
return (
);
};
```
You don't need to update component state after an update. Every component that reads the changed path re-renders when the update is applied.
An update method throws an [`ErrorInfo`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) straight away, before anything is sent, if the channel doesn't have the `OBJECT_PUBLISH` mode or the path doesn't hold an object of the right type, for example when you call `increment()` on a path with no `LiveCounter`. Otherwise it returns a promise, which rejects if the update fails. Call it from an `async` function to handle both cases in one place:
### React
```
const { object } = useObject((obj: PathObject>) => obj.get('scores').get('alice'));
const incrementScore = async () => {
try {
await object?.increment(1);
} catch (error) {
console.error('Failed to update the score', error);
}
};
```
## Handle loading and errors
The channel object resolves asynchronously, after the channel attaches and the initial synchronization completes. The hook doesn't return a status field. Instead, derive the state from `object` and `error`:
| State | Condition |
| ----- | --------- |
| Loading | `object` is `undefined` and `error` is `null` |
| Failed | `error` is not `null` |
| Ready | `object` is defined |
When the hook is ready, `value` holds the data at the subscribed path. It is `undefined` if nothing exists at that path yet.
`error` is an [`ErrorInfo`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) that describes why the channel object could not be resolved. For example, the client was created without the `LiveObjects` plugin, the channel doesn't have the `OBJECT_SUBSCRIBE` mode, or the initial synchronization failed:
### React
```
const Scoreboard = () => {
const { value, object, error } = useObject();
if (error) {
return Failed to load the game: {error.message}
;
}
if (!object) {
return Loading...
;
}
return Alice: {value?.scores?.alice ?? 0}
;
};
```
Like the other channel hooks, `useObject` also returns `connectionError` and `channelError`, which hold the reason for the most recent [connection](https://ably.com/docs/connect/states.md) or [channel](https://ably.com/docs/channels/states.md) failure. `connectionError` is reset to `null` when the connection becomes `connected` or `closed`, and `channelError` when the channel becomes `attached`:
### React
```
const { connectionError, channelError } = useObject();
```
## Type the channel object
If you use TypeScript, provide the shape of the channel object to get type-safe access to it. This is the same type you pass to [`channel.object.get
### React
```
const { value, object } = useObject();
```
When you pass a selector, annotate the selector's parameter instead. TypeScript checks the whole navigation chain, including the keys you pass to `get()`, and infers the types of `value` and `object` from the path the selector returns:
### React
```
// value: number | undefined
// object: PathObject | undefined
const { value, object } = useObject((obj: PathObject>) => obj.get('scores').get('alice'));
```
To avoid repeating the annotation, define a type alias for the channel object's `PathObject`:
### React
```
type GameObject = PathObject>;
const { value, object } = useObject((obj: GameObject) => obj.get('scores').get('bob'));
```
Without a type, the hook treats the channel object as a `LiveMap` whose entries can hold any value, so TypeScript can't check the keys you navigate to or the methods you call.
## Options
Pass an options object as the only argument, or as the second argument after a selector:
### React
```
const { value } = useObject((obj: GameObject) => obj.get('scores'), {
channelName: 'your-channel-name',
skip: !isSignedIn,
onChannelError: (error) => console.error(error.message),
});
```
| Option | Description | Type |
| ------ | ----------- | ---- |
| channelName | The name of the channel to use. A `ChannelProvider` for this channel must exist higher in the component tree. Defaults to the channel of the nearest `ChannelProvider`. | `string` |
| contextId | The ID of the `PubSubClientProvider` whose client to use, when you use [multiple clients](https://ably.com/docs/getting-started/react-hooks.md#multiple-clients). Defaults to the provider without an ID. | `string` |
| skip | When `true`, the hook doesn't attach to the channel or resolve the channel object, and `value` and `object` are `undefined`. Defaults to `false`. | `boolean` |
| onConnectionError | Called with the reason when the connection becomes `disconnected`, `suspended` or `failed`. | `(error: ErrorInfo) => unknown` |
| onChannelError | Called with the reason when the channel becomes `detached`, `suspended` or `failed`. | `(error: ErrorInfo) => unknown` |
## Return value
| Property | Description | Type |
| -------- | ----------- | ---- |
| value | A plain-data snapshot of the subscribed path, as returned by `compact()`. `undefined` while loading, or if nothing exists at the path. | The compact type of the subscribed path, or `undefined` |
| object | The `PathObject` for the subscribed path, used to navigate and to update objects. `undefined` until the channel object has synchronized, or if it can't be resolved. | `PathObject` or `undefined` |
| error | The reason the channel object could not be resolved, or `null`. | `ErrorInfo` or `null` |
| connectionError | The reason for the most recent connection failure, or `null`. | `ErrorInfo` or `null` |
| channelError | The reason for the most recent channel failure, or `null`. | `ErrorInfo` or `null` |
## Edge cases
* If the connection is `suspended`, `closing`, `closed` or `failed` when the component mounts, the hook waits, and resolves the channel object once the connection is usable again. Until then, `object` is `undefined`.
* Once resolved, `object` stays the same across a detach and reattach of the channel, so your component doesn't need to handle reattachment.
* If `channelName` changes, `object` and `value` are `undefined` until the new channel's object resolves. The hook never returns data from the previous channel.
* If the selector returns a different path, the hook unsubscribes from the old path and subscribes to the new one.
* If nothing exists at the subscribed path, `object` is still defined but `value` is `undefined`. Create the object, for example with `set()` on its parent `LiveMap`, before you call update methods on it.
* With server-side rendering, `value` and `object` are always `undefined` on the server, because the hook resolves the channel object in an effect after the component mounts. The component renders its loading state on the server and in the first client render.
## FAQ
### Do I need to attach to the channel myself?
No. The hook attaches to the channel and waits for the initial synchronization before it returns `object`.
### Can I use useObject without a ChannelProvider?
No. The channel must have a `ChannelProvider` higher in the component tree, which is where its channel modes are set. Use the `channelName` option to pick a channel other than the nearest `ChannelProvider`'s, provided that channel also has a `ChannelProvider` above the component.
### How do I avoid re-rendering on every change to the channel object?
Pass a selector that navigates to the narrowest path the component renders. The component then re-renders only when data at or below that path changes.
### Why isn't value equal to a snapshot from another component?
Each `useObject` call produces its own snapshot, so two components that read the same data get two copies. Compare the fields you need, or use `object` when you need a stable reference to a path.
## Related
* [PathObject](https://ably.com/docs/liveobjects/concepts/path-object.md): navigate, read and update objects through paths.
* [Typing](https://ably.com/docs/liveobjects/typing.md): describe the shape of the channel object in TypeScript.
* [Pub/Sub React Hooks](https://ably.com/docs/getting-started/react-hooks.md): the providers and hooks for messages and presence.
## Related Topics
- [Batch operations](https://ably.com/docs/liveobjects/batch.md): Group multiple objects operations into a single channel message to apply grouped operations atomically and improve performance.
- [Lifecycle events](https://ably.com/docs/liveobjects/lifecycle.md): Understand lifecycle events for Objects, LiveMap and LiveCounter to track synchronization events and object deletions.
- [Typing](https://ably.com/docs/liveobjects/typing.md): Type objects on a channel for type safety and code autocompletion.
- [Inband objects](https://ably.com/docs/liveobjects/inband-objects.md): Subscribe to LiveObjects updates from Pub/Sub SDKs.
- [Object storage](https://ably.com/docs/liveobjects/storage.md): Learn about LiveObjects object storage.
- [Using the REST SDK](https://ably.com/docs/liveobjects/rest-sdk-usage.md): Learn how to work with Ably LiveObjects using the REST SDK
- [Using the REST API](https://ably.com/docs/liveobjects/rest-api-usage.md): Learn how to work with Ably LiveObjects using the REST API
## Documentation Index
To discover additional Ably documentation:
1. Fetch [llms.txt](https://ably.com/llms.txt) for the canonical list of available pages.
2. Identify relevant URLs from that index.
3. Fetch target pages as needed.
Avoid using assumed or outdated documentation paths.