How to use react-async-hook - 10 common examples

To help you get started, we’ve selected a few react-async-hook examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github itchio / itch / src / renderer / Shell / Topbar.tsx View on Github external
export const Topbar = () => {
  const socket = useSocket();
  const [maximized, setMaximized] = useState(false);
  const [popover, setPopover] = useState(null);
  let profile = useProfile();

  let close = useAsyncCallback(async () => {
    await socket.query(queries.close);
  });

  let minimize = useAsyncCallback(async () => {
    await socket.query(queries.minimize);
  });

  let toggleMaximized = useAsyncCallback(async () => {
    await socket.query(queries.toggleMaximized);
  });

  useEffect(() => {
    (async () => {
      try {
        const { maximized } = await socket.query(queries.isMaximized);
        setMaximized(maximized);
      } catch (e) {
        // ignore
      }
    })();
  }, []);

  useListen(socket, packets.maximizedChanged, ({ maximized }) => {
    setMaximized(maximized);
github jamaljsr / polar / src / components / designer / lightning / actions / OpenChannelModal.tsx View on Github external
'cmps.designer.lightning.actions.OpenChannelModal',
  );
  const { nodes } = useStoreState(s => s.lightning);
  const { visible, to, from } = useStoreState(s => s.modals.openChannel);
  const { hideOpenChannel } = useStoreActions(s => s.modals);
  const { getWalletBalance, openChannel } = useStoreActions(s => s.lightning);
  const { notify } = useStoreActions(s => s.app);

  const getBalancesAsync = useAsync(async () => {
    if (!visible) return;
    for (const node of network.nodes.lightning) {
      await getWalletBalance(node);
    }
  }, [network.nodes, visible]);

  const openChanAsync = useAsyncCallback(async (payload: OpenChannelPayload) => {
    try {
      await openChannel(payload);
      hideOpenChannel();
    } catch (error) {
      notify({ message: l('submitError'), error });
    }
  });

  // flag to show the deposit checkbox if the from node balance is less than the capacity
  let showDeposit = false;
  const selectedFrom = form.getFieldValue('from') || from;
  const areSameNodesSelected = selectedFrom === (form.getFieldValue('to') || to);
  if (selectedFrom && nodes[selectedFrom] && !openChanAsync.loading) {
    const { confirmed } = nodes[selectedFrom].walletBalance || {};
    const balance = parseInt(confirmed || '0');
    const sats = form.getFieldValue('sats');
github itchio / itch / src / renderer / Gate / Form.tsx View on Github external
const passwordRef = useRef(null);
  const [password, setPassword] = useState("");
  const [passwordShown, setPasswordShown] = useState(false);
  const [totpState, setTOTPState] = useState(null);

  let togglePasswordVisibility = () => {
    setPasswordShown(!passwordShown);
  };

  let onForgotPassword = useAsyncCallback(async () => {
    await socket.query(queries.openExternalURL, {
      url: "https://itch.io/user/forgot-password",
    });
  });

  let onLogin = useAsyncCallback(async () => {
    const { error: _, ...stage } = props.stage;
    props.setState({
      type: "form",
      stage,
    });

    if (!passwordRef.current) {
      return;
    }

    if (props.stage.username === "#api-key") {
      // for integration tests
      const { profile } = await socket.call(messages.ProfileLoginWithAPIKey, {
        apiKey: passwordRef.current.value,
      });
github celo-org / celo-monorepo / packages / mobile / src / fees / CalculateFee.tsx View on Github external
function useAsyncShowError(
  asyncFunction: ((...args: Args) => Promise) | (() => Promise),
  params: Args,
  showErrorFunction: typeof showError
): UseAsyncReturn {
  const asyncResult = useAsync(asyncFunction, params)

  useEffect(
    () => {
      // Generic error banner
      if (asyncResult.error) {
        showErrorFunction(ErrorMessages.CALCULATE_FEE_FAILED)
      }
    },
    [asyncResult.error]
  )

  return asyncResult
}
github slorber / react-async-hook / example / index.tsx View on Github external
const useSearchStarwarsHero = () => {
  // Handle the input text state
  const [inputText, setInputText] = useState('');

  // Debounce the original search async function
  const debouncedSearchStarwarsHero = useConstant(() =>
    AwesomeDebouncePromise(searchStarwarsHero, 300)
  );

  const search = useAsyncAbortable(
    async (abortSignal, text) => {
      // If the input is empty, return nothing immediately (without the debouncing delay!)
      if (text.length === 0) {
        return [];
      }
      // Else we use the debounced api
      else {
        return debouncedSearchStarwarsHero(text, abortSignal);
      }
    },
    // Ensure a new request is made everytime the text changes (even if it's debounced)
    [inputText]
  );

  // Return everything needed for the hook consumer
  return {
github itchio / itch / src / renderer / Gate / index.tsx View on Github external
export const Gate = (props: {}) => {
  const socket = useSocket();
  const [loading, setLoading] = useState(true);
  const [state, setState] = useState({
    type: "form",
    stage: {
      type: "need-username",
    },
  });
  const [profiles, setProfiles] = useState([]);
  const [forgetConfirm, setForgetConfirm] = useState(
    null
  );

  const forgetProfile = useAsyncCallback(async (profile: Profile) => {
    try {
      await new Promise((resolve, reject) => {
        setForgetConfirm({ resolve, reject, profile });
      });
    } catch (e) {
      console.log(`Forget confirm was cancelled`);
      return;
    } finally {
      setForgetConfirm(null);
    }

    await socket.call(messages.ProfileForget, { profileId: profile.id });
    fetchProfiles("refresh");
  });

  let fetchProfiles = (purpose: "first-time" | "refresh") => {
github itchio / itch / src / renderer / Shell / InstallModal.tsx View on Github external
props.onClose();
        const locsRes = await socket.call(messages.InstallLocationsList, {});

        await socket.call(messages.InstallQueue, {
          game: props.game,
          upload: upload,
          queueDownload: true,
          installLocationId: locsRes.installLocations[0].id,
        });
      } catch (e) {
        setQueued(_.omit(queued, upload.id));
      }
    });

    const uninstall = useAsyncCallback(async (cave: Cave) => {
      setUninstalling(null);
      setDownloads(_.omit(downloads, cave.upload.id));
      await socket.query(queries.uninstallGame, { cave });
    });

    const [showOthers, setShowOthers] = useState(false);

    const hasUploads =
      uploads &&
      !(
        _.isEmpty(uploads.compatible) &&
        _.isEmpty(uploads.local) &&
        _.isEmpty(uploads.others)
      );

    return (
github itchio / itch / src / renderer / Shell / DownloadsButton.tsx View on Github external
const DownloadsMenu = (props: { download: Download }) => {
  const d = props.download;

  const socket = useSocket();
  const uninstall = useAsyncCallback(async () => {
    await socket.call(messages.UninstallPerform, {
      caveId: d.caveId,
    });
  });
  const discard = useAsyncCallback(async () => {
    await socket.call(messages.DownloadsDiscard, {
      downloadId: d.id,
    });
  });

  return (
    
      <button id="grid.item.discard_download" label="{<FormattedMessage">}
        onClick={discard.execute}
        loading={discard.loading}
      /&gt;
      </button><button id="grid.item.open_page" label="{<FormattedMessage">}</button>
github jamaljsr / polar / src / components / designer / bitcoind / actions / MineBlocksInput.tsx View on Github external
const MineBlocksInput: React.FC&lt;{ node: BitcoinNode }&gt; = ({ node }) =&gt; {
  const { l } = usePrefixedTranslation('cmps.designer.bitcoind.MineBlocksInput');
  const [value, setValue] = useState(6);
  const { notify } = useStoreActions(s =&gt; s.app);
  const { mine } = useStoreActions(s =&gt; s.bitcoind);
  const mineAsync = useAsyncCallback(async () =&gt; {
    try {
      await mine({ blocks: value, node });
    } catch (error) {
      notify({ message: l('error'), error });
    }
  });

  return (
    &lt;&gt;
      
        
           v &amp;&amp; setValue(v)}
github jamaljsr / polar / src / components / designer / lightning / actions / Deposit.tsx View on Github external
const Deposit: React.FC&lt;{ node: LightningNode }&gt; = ({ node }) =&gt; {
  const { l } = usePrefixedTranslation('cmps.designer.lightning.actions.Deposit');
  const [amount, setAmount] = useState(1000000);
  const { notify } = useStoreActions(s =&gt; s.app);
  const { depositFunds } = useStoreActions(s =&gt; s.lightning);
  const depositAsync = useAsyncCallback(async () =&gt; {
    try {
      await depositFunds({ node, sats: amount.toString() });
      notify({
        message: l('depositSuccess', { amount: format(amount), node: node.name }),
      });
    } catch (error) {
      notify({ message: l('depositError'), error });
    }
  });

  return (

react-async-hook

Async hook

MIT
Latest version published 3 years ago

Package Health Score

53 / 100
Full package analysis