createPartyKitPersister
The createPartyKitPersister
function creates a Persister
object that can persist the Store
to durable PartyKit storage, enabling synchronization of the same Store
across multiple clients.
createPartyKitPersister(
store: Store,
connection: PartySocket,
configOrStoreProtocol?: PartyKitPersisterConfig | "http" | "https",
onIgnoredError?: (error: any) => void,
): PartyKitPersister
Type | Description | |
---|---|---|
store | Store | The |
connection | PartySocket | The PartySocket to use for participating in the PartyKit room. |
configOrStoreProtocol? | PartyKitPersisterConfig | "http" | "https" | The |
onIgnoredError? | (error: any) => void | An optional handler for the errors that the |
returns | PartyKitPersister | A reference to the new |
As well as providing a reference to the Store
to persist, you must provide a connection
parameter which is a PartyKit PartySocket that you have already instantiated with details of the host and room.
All suitably-equipped TinyBase clients connecting to that room will get to share synchronized Store
state.
The server room's Store
is considered the source of truth. If it is a newly-created room, then calling the save
method on this Persister
will initiate it. If, however, there is already a Store
present on the server, the save
method will fail gracefully.
In general, you are strongly recommended to use the auto-save and auto-load functionality to stay in sync incrementally with the server, as per the example below. This pattern will handle newly-created servers and newly-created clients - and the synchronization involved in joining rooms, leaving them, or temporarily going offline.
See the PartyKit client socket API documentation for more details.
Example
This example creates a PartyKitPersister
object and persists the Store
to the browser's IndexedDB storage.
const store = createStore()
.setTable('pets', {fido: {species: 'dog'}})
.setTable('species', {dog: {price: 5}})
.setValues({open: true});
const partySocket = new PartySocket({
host: PARTYKIT_HOST,
room: 'my_room',
});
const persister = createPartyKitPersister(store, partySocket);
await persister.startAutoLoad();
await persister.startAutoSave();
// Store will now be synchronized with the room.
persister.destroy();
Since
4.3.0