Skip to content

Promises module

Dmitry Usik edited this page Apr 3, 2022 · 26 revisions

useAsync

The main purpose of this hook is to introduce the hooks approach for async functions and connect the results of an async function with the internal variables that are managed by the useState hook.

Receives:

  • toCall - the async function which should be invoked.
  • options:
  • setIsLoading - the function which sets the boolean value which is managed by the useState hook. Represents the loading state.
  • setResult - the function which sets the T value which is managed by the useState hook. Represents the result that is returned from the async function.
  • setError - the function which sets the AppError value which is managed by the useState hook. Represent the error that is caused by the async method.

Returns:

  • doAsync - the function which will invoke toCall.

Usage

import { useAsync } from '~modules/promises';

const [isLoading, setIsLoading] = useState<boolean>();
const [result, setResult] = useState<T>();
const [error, setError] = useState
const doAsync = useAsync();

useEffect(() => {
  const toCall = async () => {
    ...the body of the async function
  };

  doAsync(toCall, { setIsLoading, setResult, setError });
}, [doAsync]);

useRetriever

The main purpose of this hook is to retrieve the data asynchronously, using the hooks approach.

Receives:

  • retrieveFn - the async function which retrieves the data. Should be wrapped to the useCallback hook.
  • defaultValue - default value for the data.
  • runOnFocus- should the async function be invoked every time a screen is focused, or not. false by default.

Returns:

  • [result, isLoadingResult, error, retreiveFn] - the result of the retrieveFn, the loading state, an error, and the function for manual retrieving.

Usage

import { useRetriever } from '~modules/promises';

const retriveFn = useCallback(() => someAsyncFunction(), []);
const [result, isLoadingResult] = useRetriver(retrieve, undefined, true);

useTimeout

The main purpose of this hook is to make it possible to call setTimeout using the hooks approach.

Returns:

  • [withTimeout, cancel] - the function which receives callback and timeout and the function which cancels the timeout.

Usage

import { useTimeout } from '~modules/promises';

const [withTimeout, cancel] = useTimeout();

withTimeout(() => {}, 1000);

useInterval

The main purpose of this hook is to make it possible to call setInterval using the hooks approach.

Returns:

  • [withInterval, cancel] - the function which receives callback and interval and the function which cancels the interval.

Usage

import { useInterval } from '~modules/promises';

const [withInterval, cancel] = useInterval();

withInterval(() => {}, 1000);
Clone this wiki locally