monitor.add()

Using monitor.add(), specific items of any type may manually be added to the monitored context.

Warning: This is a low-level API. Yozo takes care of adding the correct items to the monitored contexts in most cases. Overusing this API may lead to hard-to-debug errors.

Syntax

monitor.add(type, ...things);

Parameters

type
A registered monitorable type. By default, either 'undo' or 'live'.
...things
The items to add to the monitored context. The type determines what type of data should be passed; for 'undo', a single callback function should be provided. For 'live', two additional arguments are expected; a live variable and an event type to listen for.

Return value

None (undefined).

Details

If a monitored context exists, and the provided type exists, then the item or items are added to the context. If a context or the type does not exist, then nothing happens. In other words; it is safe to call even if a monitored context is not guaranteed.

Calls to monitor.add() within monitor.ignore() calls are ignored.

Examples

Fetch request

When using fetch() inside an effect, it may be desirable to abort the request if it hasn't finished before the effect is re-run. To do so, we may use monitor.add() to add a cleanup callback to the monitored context.

effect(() => { const controller = new AbortController(); const { signal } = controller; monitor.add('undo', () => controller.abort()); const response = await until(fetch('/resource.json', { signal })); // do things with the response… });

While this is a quick way to resolve the issue of overlapping requests, note that we don't actually need it for a case like this. Specifically, until() does an "early return" of sorts when the context is undone before its argument has resolved. If we really need this type of functionality, then we may avoid using monitor.add() altogether by using a Flow, which have a more fleshed out API for adding cleanup callbacks. It allows us to create more readable and reusable code.

function monitorableFetch(url, options){ const controller = new AbortController(); const { signal } = controller; return new Flow(trigger => { fetch(url, { ...options, signal }).then(trigger); }).cleanup(() => { controller.abort(); }).once(); } effect(() => { const response = await until(monitorableFetch('/resource.json')); // do things with the response… });

Not only does this avoid monitor.add(), but creating a flow allows for methods such as .stop(), .until(), or .or() which allows for much simpler expressions regarding fetching later on. For example, we might then create a timeout for a fetch request using

await monitorableFetch('/heavy_operation').until(timeout(5000));

In short, it is best to avoid monitor.add() simply because it is a lower-level API that is better off abstracted away (which Yozo has already done itself).

See also