All Downloads are FREE. Search and download functionalities are using the official Maven repository.

web.lib.core.components.data-loader.tsx Maven / Gradle / Ivy

There is a newer version: 37
Show newest version
import * as React from 'react';
import { useEffect, useState } from 'react';
import { effectSafety, EffectSafety, Loader } from './stuff';

export function DataLoader(props: { loader: () => Promise, deps?: any[], children: ((arg: T) => any) | React.ReactNode }) {
  const [ data, setData ] = useState<{ result: T } | undefined>(undefined);
  const [ error, setError ] = useState();
  const loadData = async (safety: EffectSafety) => {
    try {
      const result = await props.loader();
      safety.callSafely(() => setData({ result }));
    } catch (e) {
      safety.callSafely(() => setError(e));
    }
  };
  useEffect(() => {
    const safety = effectSafety();
    setData(undefined);
    loadData(safety);
    return safety.unload;
  // eslint-disable-next-line 
  }, ([JSON.stringify(props.deps)] || []));
  if (!!data) {
    if (props.children instanceof Function) {
      return props.children(data.result);
    }
    return props.children;
  }
  return ();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy