npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@draftup/react-use-promise

v1.0.2

Published

Custom React hook to manage promises

Downloads

7

Readme

React use promise

Custom React hook to manage promises.

semantic-release

Install

npm i -S @draftup/react-use-promise

Highlights

  • Automatic promise cancellation:
    • when componet has been unmounted,
    • when another promise has been injected.
  • React way error handling.
  • Typescript and Flow type definitions included.

Usage

Basic example

usePromise is a custom React hook:

const [promiseState, promiseInjector] = usePromise();

Upon it's initialization promiseState is null. Once you inject a promise using promiseInjector first time promiseState becomes an object with a following signature:

type PromiseState<ValueType> = {
  pending: boolean;
  resolved: boolean;
  rejected: boolean;
  value: null | ValueType;
  error: null | Error;
};

Here's a simple example of how to use usePromise hook in your React component:

import { usePromise } from "@draftup/react-use-promise";

const submitService = async () => {
  // Some kind of asynchronous operation goes here.
};

const Component = () => {
  const [promiseState, injectPromise] = usePromise();

  const handleClick = React.useCallback(() => {
    injectPromise(submitService());
  }, [injectPromise]);

  if (promiseState && promiseState.pending) {
    return <span>processing...</span>;
  }

  if (promiseState && promiseState.resolved) {
    return <span>succeeded</span>;
  }

  if (promiseState && promiseState.rejected) {
    return <span>failed</span>;
  }

  return <button onClick={handleClick}>submit</button>;
};

Edit use-promise-basic

Error handling

By default usePromise will throw away any instance of Error constructor that was either throwed or returned by injected promise. You should take care of this errors by using error boundaries:

const submitService = async () => {
  throw new Error("Error message");
};

const Root = () => (
  <ErrorBoundary>
    <Component />
  </ErrorBoundary>
);

const Component = () => {
  const [promiseState, injectPromise] = usePromise();

  const handleClick = React.useCallback(() => {
    injectPromise(submitService());
  }, [injectPromise]);

  // Error instance will be throwed away and will bubble up
  // to the closest error boundary you set.

Edit use-promise-error-propagation


But there are cases when you want to handle some errors locally. To make it possible there are an errorsToKeep option you can pass on hook initialization. It takes an array of error constructors whose instances you want to handle locally:

const [promiseState, injectPromise] = usePromise({
  errorsToKeep: [MyError]
});

With above configuration any instance of MyError throwed or returned by promise will end up in a promiseState.error property so you can handle it locally:

const submitService = async () => {
  throw new MyError("My error message");
};

const Component = () => {
  const [promiseState, injectPromise] = usePromise({
      errorsToKeep: [MyError]
  });

  const handleClick = React.useCallback(() => {
    injectPromise(submitService());
  }, [injectPromise]);

  if (promiseState && promiseState.error) {
    return(
        <span>{promiseState.error.message}</span>
    )
  }

  // ...

Edit use-promise-error-local


Take a note that your custom error constructors must be inherited from native Error constructor if you are going to throw them from inside you promise:

// This will end up with a custom TypeError throwed away:
// class MyError {}

class MyError extends Error {}

const submitService = async () => {
  throw new MyError("My error message");
};

License

This project is MIT licensed.