import { IElementState, IElementEffect } from "../types"; import { isArgsEqual } from "../util"; export const useEffectHook = (state: IElementState, fn: () => any, deps?: any[]) => { if (state.isFirstTick) { let dispose: any; try { dispose = fn(); } catch (e) { state.error = e; return; } const newEffect: IElementEffect = { deps, dispose: dispose && typeof dispose === "function" ? dispose : undefined, }; state.effects.push(newEffect); return; } const currentEffectNumber = state.tickState.currentEffectNumber; state.tickState.currentEffectNumber++; const effect = state.effects[currentEffectNumber]; if (!effect) { throw new Error("Expected effect with number " + currentEffectNumber); } const existsDeps = effect.deps || []; const newDeps = deps || []; if (!(existsDeps.length === 0 && newDeps.length === 0) && existsDeps.length !== newDeps.length) { throw new Error("Dependencies not equal, old version of effect has dependencies and new version not has"); } const isDepsEqual = isArgsEqual(effect.deps, deps); if (effect.deps && deps && isDepsEqual) { return; } if ((!effect.deps && !deps) || !isDepsEqual) { let dispose: any; try { dispose = fn(); } catch (e) { state.error = e; return; } effect.dispose = dispose && typeof dispose === "function" ? dispose : undefined; effect.deps = deps; } };