Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 1.53 KB

useAsync.md

File metadata and controls

50 lines (37 loc) · 1.53 KB

useAsync

Reduces littering in your component by abstracting logic and management of multiple states.

Arguments

  • asyncFunction {function}: async function to be executed
  • immediate {boolean}: determens wether or not asyncFunction should be executed opon initialization, defualt true

Returns

  • 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

Usage

// ---------- 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>
  </>
);