-
Notifications
You must be signed in to change notification settings - Fork 2
Promises module
Dmitry Usik edited this page Apr 3, 2022
·
26 revisions
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.
-
toCall
- the async function which should be invoked. -
options
: -
setIsLoading
- the function which sets the boolean value which is managed by theuseState
hook. Represents the loading state. -
setResult
- the function which sets theT
value which is managed by theuseState
hook. Represents the result that is returned from the async function. -
setError
- the function which sets theAppError
value which is managed by theuseState
hook. Represent the error that is caused by the async method.
-
doAsync
- the function which will invoketoCall
.
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]);
The main purpose of this hook is to retrieve the data asynchronously, using the hooks approach.
-
retrieveFn
- the async function which retrieves the data. Should be wrapped to theuseCallback
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.
-
[result, isLoadingResult, error, retreiveFn]
- the result of theretrieveFn
, the loading state, an error, and the function for manual retrieving.
import { useRetriever } from '~modules/promises';
const retriveFn = useCallback(() => someAsyncFunction(), []);
const [result, isLoadingResult] = useRetriver(retrieve, undefined, true);
The main purpose of this hook is to make it possible to call setTimeout
using the hooks approach.
-
[withTimeout, cancel]
- the function which receives callback and timeout and the function which cancels the timeout.
import { useTimeout } from '~modules/promises';
const [withTimeout, cancel] = useTimeout();
withTimeout(() => {}, 1000);
The main purpose of this hook is to make it possible to call setInterval
using the hooks approach.
-
[withInterval, cancel]
- the function which receives callback and interval and the function which cancels the interval.
import { useInterval } from '~modules/promises';
const [withInterval, cancel] = useInterval();
withInterval(() => {}, 1000);