createCustomPersister
The createCustomPersister
function creates an Persister
object that you can configure to persist the Store
in any way you wish.
createCustomPersister(
store: Store,
getPersisted: () => Promise<undefined | null | string>,
setPersisted: (json: string) => Promise<void>,
startListeningToPersisted: (didChange: Callback) => void,
stopListeningToPersisted: Callback,
): Persister
Type | Description | |
---|---|---|
store | Store | The |
getPersisted | () => Promise<undefined | null | string> | An asynchronous function which will fetch JSON from the persistence layer (or |
setPersisted | (json: string) => Promise<void> | An asynchronous function which will send JSON to the persistence layer. |
startListeningToPersisted | (didChange: Callback) => void | A function that will register a |
stopListeningToPersisted | Callback | A function that will unregister the listener from the underlying changes to the persistence layer. |
returns | Persister | A reference to the new Persister object. |
As well as providing a reference to the Store
to persist, you must provide functions that handle how to fetch, write, and listen to, the persistence layer.
The other creation functions (such as the createSessionPersister
function and createFilePersister
function, for example) all use this function under the covers. See those implementations for ideas on how to implement your own Persister
types.
This example creates a custom Persister
object and persists the Store
to a local string called storeJson
and which would automatically load by polling for changes every second.
const store = createStore().setTables({pets: {fido: {species: 'dog'}}});
let storeJson;
let interval;
const persister = createCustomPersister(
store,
async () => storeJson,
async (json) => (storeJson = json),
(didChange) => (interval = setInterval(didChange, 1000)),
() => clearInterval(interval),
);
await persister.save();
console.log(storeJson);
// -> '{"pets":{"fido":{"species":"dog"}}}'
storeJson = '{"pets":{"fido":{"species":"dog","color":"brown"}}}';
await persister.load();
console.log(store.getTables());
// -> {pets: {fido: {species: 'dog', color: 'brown'}}}
persister.destroy();