From 406ffd7d3d430a5f91328e85a5475a9cfdc596c4 Mon Sep 17 00:00:00 2001 From: sagar Date: Thu, 9 Jan 2020 15:45:48 +0530 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=A6=20NEW:=20useAsync=20hook=20add?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/UseAsync.md | 72 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 snippets/UseAsync.md diff --git a/snippets/UseAsync.md b/snippets/UseAsync.md new file mode 100644 index 000000000..5f717044a --- /dev/null +++ b/snippets/UseAsync.md @@ -0,0 +1,72 @@ +--- +title: useAsync +tags: react,intermediate,hook +--- + + +The `useAsync` hook is used to bind asynchronous call and handle different states like loading, error, and value. According to the state of an asynchronous call, we can render different states like loading, error and value state. + +**Explanation:** +In `useAsync` hook we need to pass the handler function and that will be called after calling the `run` method. Once `run` get's called we're changing loading, error and value field according to asynchronous call response. + +```js +const useAsync = (fn, options = {}) => { + const autoRun = options.autoRun || false + + const [state, setState] = React.useState({ + error: null, + loading: false, + value: null, + }) + + const handleStateChange = args => { + setState({ ...state, ...args }) + } + + const run = async (args = null) => { + try { + handleStateChange({ loading: true, error: null }) + const value = await fn(args) + handleStateChange({ loading: false, value: value || null, error: null }) + } catch (error) { + handleStateChange({ loading: false, value: null, error }) + } + } + + React.useEffect(() => { + if (autoRun) { + run() + } + }, [autoRun]) + + return { + state, + setState, + run, + } +} +``` + +**Usages** +```jsx +const App = () => { + const handleSubmit = () => { + const url = "https://jsonplaceholder.typicode.com/todos" + return fetch(url).then(response => response.json()) + } + + const submission = useAsync(handleSubmit, { autoRun: false }) + + return ( +
+ {submission.value &&
{submission.value}
} + +
+ ) +} +```