@mathislair/mtbreactive-react
v0.1.0
Published
React hook (`useReactive`) on top of @mathislair/mtbreactive-client. Subscribe a component to a (channel, scope) and re-render as snapshot/change frames arrive.
Maintainers
Readme
@mathislair/mtbreactive-react
React hook (useReactive) on top of @mathislair/mtbreactive-client. Subscribe a component to a (channel, scope) and re-render as snapshot/change frames arrive.
Install
npm install @mathislair/mtbreactive-react @mathislair/mtbreactive-clientSetup
Wrap your app (or a relevant subtree) in ReactiveProvider:
import { ReactiveClient } from '@mathislair/mtbreactive-client';
import { ReactiveProvider } from '@mathislair/mtbreactive-react';
const client = new ReactiveClient('ws://localhost:8080/ws');
export function App() {
return (
<ReactiveProvider client={client}>
<Routes />
</ReactiveProvider>
);
}Usage
import { useReactive } from '@mathislair/mtbreactive-react';
interface Message { id: number; body: string }
export function Chat({ roomId }: { roomId: number }) {
const messages = useReactive<Message>(
'message',
{ col: 'conversation_id', value: roomId },
);
return (
<ul>
{messages.map((m) => <li key={m.id}>{m.body}</li>)}
</ul>
);
}The hook applies frames to a list:
snapshotreplaces the list.afterInsertappends (or upserts on duplicate primaryKey).afterUpdatemerges into the existing row, preserves position.afterDeletedrops by primaryKey.
The reducer (applyFrame) lives in @mathislair/mtbreactive-client and is re-exported here. Composite primary keys are supported.
Options
| Option | Purpose |
| ------------- | ------------------------------------------------------------------------ |
| client | Override the client from <ReactiveProvider>. Useful in tests. |
| initial | Rows shown until the first frame arrives (e.g. SSR / route-loader data). |
| onError(c) | Notified when an error frame arrives (forbidden, unknown_channel, ...). |
License
MIT
