storeon-until
Utility for awaiting Storeon events.
It size is 67 B (minified and gzipped) and uses Size Limit to control size.
Overview
The goal of this tiny library is provide the easy way to awaiting occurrence of the particular
storeon event.
Install
npm i storeon-until --save
Usage
Simple usage
From version 1.1.0 we provided the shortcut to inline the await statement with dispatch.
The returned promise contains the dispatch
function which allows to dispatch the event on store,
that function returns the promise again.
import { createStoreon } from "storeon";
import { until } from "storeon-until";
const store = createStoreon([]);
store.on('loadDocument', async (state, id) => {
const document = await fetch(`http://some.document.com/${id}`);
store.dispatch('documentLoaded', {id, document});
});
store.on('documentLoaded', (_, {id, document}) => ({
id,
document
}));
const {id, document} =
await until(store, 'documentLoaded', (_, {id}) => id === 'id1')
.dispatchOver('loadDocument', 'id1');
console.log(document);
const {id, document} =
await until(store, '@changed', ({id}) => id === 'id2')
.dispatchOver('loadDocument', 'id2');
console.log(document);
More verbose usage
import { createStoreon } from "storeon";
import { until } from "storeon-until";
const store = createStoreon([]);
store.on('loadDocument', async (state, id) => {
const document = await fetch(`http://some.document.com/${id}`);
store.dispatch('documentLoaded', {id, document});
});
store.on('documentLoaded', (_, {id, document}) => ({
id,
document
}));
const documentLoadedPromise = until(store, 'documentLoaded', (_, {id}) => id === 'id1');
store.dispatch('loadDocument', 'id1');
const {id, document} = await documentLoadedPromise;
console.log(document);
const statePromise = until(store, '@changed', ({id}) => id === 'id2');
store.dispatch('loadDocument', 'id2');
const {id, document} = await statePromise;
console.log(document);
Caution
Please notice, that we should always use until
utility to create promise before the event dispatch
as dispatched event can run synchronously.
Api
until
- is function which returns UntilResult
(which is promise) of requested event data. Params:
store
the storeevent
the event which we are waiting forcondition
- (optional) - the function which gets state, and event data and have to return true
if promise has to be resolved for that state or data
UntilResult
dispatchOver
- function which allows to dispatch event on the store in await place