Open
Description
I love how GraphQL <QueryRender />
have render props that return
({ loading, props, error, retry })
I often find myself writing the same logic around form submit buttons and other various UI where I need to know whether my async function is loading, had an error or the result.
I'm proposing an API like this:
const sleep = time => () => new Promise(done => setTimeout(done, time));
function App() {
const [onClick, { loading, error }] = useAsyncFunction(sleep(500));
return (
<>
<pre>
error: {JSON.stringify(error)}
<br />
loading: {JSON.stringify(loading)}
</pre>
<button onClick={onClick}>{loading ? "Loading..." : "Load"}</button>
</>
);
}
I think we should also support a delayMs
option that will tell our async function only resolve after a given ms .. it should work like this:
const sleep = () => Promise.resolve();
function App() {
const [onClick, { loading, error }] = useAsyncFunction(sleep, { delayMs: 500 });
return (
<>
<pre>
error: {JSON.stringify(error)}
<br />
loading: {JSON.stringify(loading)}
</pre>
<button onClick={onClick}>{loading ? "Loading..." : "Load"}</button>
</>
);
}
I have most of the code working, I'll just need to add type defintions and some better testing in this repo: https://github.com/hanford/async-function
Once that's done, I'll transfer the ownership (aiming to be complete tomorrow morning)
Metadata
Metadata
Assignees
Labels
No labels