TinyBase logoTinyBase

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
TypeDescription
storeStore

The Store to persist.

connectionPartySocket

The PartySocket to use for participating in the PartyKit room.

configOrStoreProtocol?PartyKitPersisterConfig | "http" | "https"

The PartyKitPersisterConfig configuration for the Persister, (or a string to specify a HTTP protocol to use, defaulting to 'https').

onIgnoredError?(error: any) => void

An optional handler for the errors that the Persister would otherwise ignore when trying to save or load data. This is suitable for debugging persistence issues in a development environment.

returnsPartyKitPersister

A reference to the new PartyKitPersister object.

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