import { useMemo, useState, useCallback, useEffect } from 'react';

const cacheMemory = {};
function useHttp(key, fetcher) {
  const cacheKey = useMemo(() => Array.isArray(key) ? key.map(v => typeof v === 'object' ? JSON.stringify(v) : v).join('-') : JSON.stringify(key), [key]);
  const [state, setState] = useState({
    data: cacheMemory[cacheKey],
    error: undefined,
    loadding: true,
    httpKey: Date.now()
  });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const promiseFetcher = useMemo(() => fetcher(key), [cacheKey, state.httpKey]);
  const update = useCallback(() => {
    delete cacheMemory[cacheKey];
    setState(old => ({
      ...old,
      httpKey: Date.now()
    }));
  }, [cacheKey]);
  useEffect(() => {
    setState(old => old.loadding ? old : {
      ...old,
      loadding: true
    });
    promiseFetcher.then(res => {
      cacheMemory[cacheKey] = res;
      setState(old => ({
        ...old,
        data: res,
        loadding: false
      }));
    }).catch(e => {
      setState(old => ({
        ...old,
        error: e,
        loadding: false
      }));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [promiseFetcher, cacheKey]);
  return {
    update,
    data: state.data,
    error: state.error,
    loadding: state.loadding
  };
}

export { useHttp as default };
//# sourceMappingURL=index.js.map
