useAsyncHook

    0

    0

    The following code is a function called App. Inside of the App function, there is a useAsync function that takes two arguments: a function and a boolean. The useAsync function will first call the function passed in with the false argument, then it will call the function passed in with the true argument. If the function passed in with the true argument is successful, the App function will returns a div with the following values:

    • If the status is "idle", the div will have the following text: "Start your journey by clicking a button."
    • If the status is "success", the div will have the following text: "{value}"
    • If the status is "error", the div will have the following text: "{error}"

    If the function passed in with the false argument is successful, the App function will return the following div:

    • If the status is "idle", the div will have the following text: "Loading...

    Library: react

    import React, { useState, useEffect, useCallback } from "react";
    
    
    // Usage
    function App() {
      const { execute, status, value, error } = useAsync(myFunction, false);
      return (
        <div>
          {status === "idle" && <div>Start your journey by clicking a button</div>}
          {status === "success" && <div>{value}</div>}
          {status === "error" && <div>{error}</div>}
          <button onClick={execute} disabled={status === "pending"}>
            {status !== "pending" ? "Click me" : "Loading..."}
          </button>
        </div>
      );
    }
    // An async function for testing our hook.
    // Will be successful 50% of the time.
    const myFunction = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const rnd = Math.random() * 10;
          rnd <= 5
            ? resolve("Submitted successfully πŸ™Œ")
            : reject("Oh no there was an error 😞");
        }, 2000);
      });
    };
    // Hook
    const useAsync = (asyncFunction, immediate = true) => {
      const [status, setStatus] = useState("idle");
      const [value, setValue] = useState(null);
      const [error, setError] = useState(null);
      // The execute function wraps asyncFunction and
      // handles setting state for pending, value, and error.
      // useCallback ensures the below useEffect is not called
      // on every render, but only if asyncFunction changes.
      const execute = useCallback(() => {
        setStatus("pending");
        setValue(null);
        setError(null);
        return asyncFunction()
          .then((response) => {
            setValue(response);
            setStatus("success");
          })
          .catch((error) => {
            setError(error);
            setStatus("error");
          });
      }, [asyncFunction]);
      // Call execute if we want to fire it right away.
      // Otherwise execute can be called later, such as
      // in an onClick handler.
      useEffect(() => {
        if (immediate) {
          execute();
        }
      }, [execute, immediate]);
      return { execute, status, value, error };
    };
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.