Reduces littering in your component by abstracting logic and management of multiple states.
asyncFunction {function}
: async function to be executedimmediate {boolean}
: determens wether or not asyncFunction should be executed opon initialization, defualt true
- state {object}: contains three propertys: pending, value and error.
- pending {boolean}: Indicates whether or not a value is pending, default false
- value {*}: Contains the resolved value from asyncFunction, default null
- error {*}: Contains the rejected value from asyncFunction, default null
- execute {function}: that executes the provided function asyncFunction and updates the state, depending on resolve or reject
// ---------- Logic ---------- \\
import { useAsync } from "bjork_react-hookup";
import Async from "./Async";
const delayedValue = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
let number = Math.floor(Math.random() * 10);
number >= 3 ? resolve("🤯") : reject("🤬");
}, 2000);
});
const AsyncContainer = () => {
const [{ pending, value, error }, execute] = useAsync(delayedValue, false);
return <Async props={{ pending, value, error, execute }} />;
};
// ---------- Visual ---------- \\
const Async = ({ props: { pending, value, error, execute } }) => (
<>
<p>{value ? value : error ? error : "🏜"}</p>
<button onClick={() => (!pending ? execute() : "")}>
{pending ? "pending ..." : "fetch"}
</button>
</>
);