2.10.0 • Published 20 days ago

@marianmeres/fetch-store v2.10.0

Weekly downloads
-
License
MIT
Repository
github
Last release
20 days ago

@marianmeres/fetch-store

Store utility for collecting results and meta info of any type of async work. Typically used for http requests.

Install

$ npm i @marianmeres/fetch-store

Basic example

// foo-store.js
const foo = createFetchStore(async () => {
	const r = await fetch('foo.json');
	if (!r.ok) throw new Error('Not OK!');
	return await r.json();
});
<!--FooComponent.svelte-->
<script>
    onMount(foo.fetch)
</script>

{#if $foo.isFetching}
    <Spinner />
{:else if $foo.lastFetchError}
    <Error error={$foo.lastFetchError} />
{:else}
    <Foo foo={$foo.data} />
{/if}

Api

const store = createFetchStore<T>(
    // the async worker
    fetchWorker: (...args) => Promise<any>,
    // optional, initial `data` value of the store
    initial?: T = null,
    // optional, used to modify data returned by fetchWorker... (usefull for various
    // data update strategies, like merge/deepmerge/set etc)
    dataFactory?: (raw: any, old?: any) => T = null,
    // options (see source)
    options? = null
);

// subscription
store.subscribe((v) => {
    // main result
    // v.data: T;

    // meta
    // v.isFetching: boolean;
    // v.lastFetchStart: Date;
    // v.lastFetchEnd: Date;
    // v.lastFetchError: Date;
    // v.successCounter: number;
});

// instance api

// do the async work
store.fetch(...args): Promise<T>;

// do the async work, but do not update meta
store.fetchSilent(...args): Promise<T>;

// do the async work only once (if within threshold since last)
store.fetchOnce(args: any[], thresholdMs: number): Promise<void>;

// to reset internal meta store
store.reset();
store.resetError();

// for manual hackings
store.getInternalDataStore();
2.10.0

20 days ago

2.9.0

1 month ago

2.8.1

1 month ago

2.8.0

1 month ago

2.7.0

1 month ago

2.6.0

1 month ago

2.5.1

1 month ago

2.5.0

2 months ago

2.3.0

2 months ago

2.4.0

2 months ago

2.2.0

4 months ago

2.1.0

5 months ago

2.0.0

5 months ago

1.2.0

5 months ago

1.1.2

5 months ago

1.1.0

5 months ago

1.0.3

1 year ago

1.0.2

1 year ago