TinyBase logoTinyBase

addWillSetContentCallback

The addWillSetContentCallback method registers a WillSetContentCallback that will be called before Content is set in the Store.

addWillSetContentCallback(callback: WillSetContentCallback): Middleware
TypeDescription
callbackWillSetContentCallback

The WillSetContentCallback to register.

returnsMiddleware

A reference to the Middleware object, for chaining.

The callback can transform the Content or return undefined to prevent the write. Multiple callbacks can be registered and they are called sequentially, each receiving the (possibly transformed) Content from the previous callback.

Example

This example registers a callback that prevents setting Content with empty Tables in the pet store.

import {createMiddleware, createStore} from 'tinybase';

const store = createStore();
const middleware = createMiddleware(store);

middleware.addWillSetContentCallback(([tables, values]) =>
  Object.keys(tables).length > 0 ? [tables, values] : undefined,
);

store.setContent([{}, {open: true}]);
console.log(store.getContent());
// -> [{}, {}]

store.setContent([{pets: {fido: {species: 'dog'}}}, {}]);
console.log(store.getContent());
// -> [{pets: {fido: {species: 'dog'}}}, {}]

middleware.destroy();

Since

v8.0.0