👌 IMPROVE: semicolons add

This commit is contained in:
sagar
2020-01-09 22:05:12 +05:30
parent 103bb10639
commit 80414e1f9c

View File

@ -13,57 +13,61 @@ A hook that handles asynchronous calls.
```jsx ```jsx
const useAsync = (fn, options = {}) => { const useAsync = (fn, options = {}) => {
const [value, setValue] = React.useState(null) const [value, setValue] = React.useState(null);
const [error, setError] = React.useState(null) const [error, setError] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false) const [isLoading, setIsLoading] = React.useState(false);
const autoRun = options.autoRun || false const autoRun = options.autoRun || false;
const run = async (args = null) => { const run = async (args = null) => {
try { try {
setIsLoading(true) setIsLoading(true);
const value = await fn(args) const value = await fn(args);
setIsLoading(false) setIsLoading(false);
setError(null) setError(null);
setValue(value) setValue(value);
} catch (error) { } catch (error) {
setIsLoading(false) setIsLoading(false);
setError(error) setError(error);
setValue(null) setValue(null);
} }
} };
React.useEffect(() => { React.useEffect(() => {
if (autoRun) { if (autoRun) {
run() run();
} }
}, [autoRun]) }, [autoRun]);
return { return {
value, value,
error, error,
isLoading, isLoading,
run, run,
} };
} };
``` ```
```jsx ```jsx
const App = () => { const App = () => {
const handleSubmit = (args) => { // args { foo: bar } const handleSubmit = args => {
const url = "https://jsonplaceholder.typicode.com/todos" // args { foo: bar }
return fetch(url).then(response => response.json()) const url = "https://jsonplaceholder.typicode.com/todos";
} return fetch(url).then(response => response.json());
};
const submission = useAsync(handleSubmit, { autoRun: false }) const submission = useAsync(handleSubmit, { autoRun: false });
return ( return (
<div> <div>
<button onClick={() => submission.run({ foo: "bar" })} disabled={submission.isLoading}> <button
{submission.isLoading ? 'Loading...': 'click me'} onClick={() => submission.run({ foo: "bar" })}
disabled={submission.isLoading}
>
{submission.isLoading ? "Loading..." : "click me"}
</button> </button>
<pre>{JSON.stringify(submission.value, null, 2)}</pre> <pre>{JSON.stringify(submission.value, null, 2)}</pre>
</div> </div>
) );
} };
``` ```