Skip to content

Latest commit

 

History

History
35 lines (28 loc) · 730 Bytes

useAsyncFn.md

File metadata and controls

35 lines (28 loc) · 730 Bytes

useAsyncFn

React钩子返回状态和async函数或返回promise的函数的回调。 状态与useAsync的形状相同。

Usage

import {useAsyncFn} from 'react-use';

const Demo = (url) => {
  const [state, fetch] = useAsyncFn(async () => {
    const response = await fetch(url);
    const result = await response.text();
    return result
  }, [url]);

  return (
    <div>
      {state.loading
        ? <div>Loading...</div>
        : state.error
          ? <div>Error: {state.error.message}</div>
          : state.value && <div>Value: {state.value}</div>
      }
      <button onClick={() => fetch()}>Start loading</button>
    </div>
  );
};

Reference

useAsyncFn(fn, deps?: any[]);