UNPKG

atomico

Version:

Atomico is a small library for the creation of interfaces based on web-components, only using functions and hooks.

47 lines (39 loc) 1.4 kB
import './chunk/constants.js'; import { a as isEqualArray } from './chunk/utils.js'; import { useState, useEffect } from './core.js'; const LAZY_STATE_LOADING = "loading"; const LAZY_STATE_ERROR = "error"; const LAZY_STATE_DONE = "done"; function useLazy(callback, run, initWithLoading) { let initialState = initWithLoading ? [LAZY_STATE_LOADING] : []; let [state, setState] = useState(initialState); useEffect(() => { if (run) { if (!initWithLoading) { setTimeout(() => { if (run) setState([LAZY_STATE_LOADING]); }, 50); } callback() .then(md => { if (run) setState([LAZY_STATE_DONE, md.default || md]); run = false; }) .catch(e => { if (run) setState([LAZY_STATE_ERROR]); run = false; }); return () => { run = false; setState(state => isEqualArray(state, initialState) ? state : [LAZY_STATE_LOADING] ); }; } }, [run]); return state; } export { LAZY_STATE_DONE, LAZY_STATE_ERROR, LAZY_STATE_LOADING, useLazy }; //# sourceMappingURL=use-lazy.js.map