TinyBase logoTinyBase

addWillSetValueCallback

The addWillSetValueCallback method registers a WillSetValueCallback that will be called before any Value is set in the Store.

addWillSetValueCallback(callback: WillSetValueCallback): Middleware
TypeDescription
callbackWillSetValueCallback

The WillSetValueCallback to register.

returnsMiddleware

A reference to the Middleware object, for chaining.

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

Example

This example registers a callback that clamps the 'limit' Value to the maximum capacity of the pet store.

import {createMiddleware, createStore} from 'tinybase';

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

middleware.addWillSetValueCallback((valueId, value) =>
  valueId === 'limit' && typeof value === 'number'
    ? Math.min(50, Math.max(0, value))
    : value,
);

store.setValue('limit', 100);
console.log(store.getValue('limit'));
// -> 50

middleware.destroy();

Since

v8.0.0