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

react-promise-utils

v0.2.0

Published

Minimalist utils for handling loading states and async values in React.

Downloads

4

Readme

react-promise-utils

Minimalist utils for handling loading states and async values in React.

Quick Example

npm install react-promise-utils
import Resolve from 'react-promise-utils/Resolve';
import { usePromiseState } from 'react-promise-utils/usePromiseState';

function Component() {
  const [itemsPromise, fetchItems] = usePromiseState(
    (offset = 0, limit = 20) => fetch(`/items?offset=${offset}&limit=${limit}`)
      .then(res => res.json())
  );

  return (
    <Resolve promise={itemsPromise} render={({ items, offset, total }) => (
      <>
        <ItemsList items={items} />
        <button
          disabled={offset + items.length >= total}
          onClick={() => fetchItems(offset + items.length)}
        >
          Next
        </button>
      </>
    )} />
  );
}

<Resolve> Component

A wrapper component abstacting common data fetching patterns.

  • Preserves last rendered elements while new data is fetched.
  • Prevents slow responses from clobbering new ones.
  • Tries to help with ARIA live regions.

Props:

interface ResolveProps<T> {
  // Any promise.
  promise: Promise<T>;

  // Callback with single parameter: the resolved value of the promise.
  render: (data: T) => ReactElement;

  // Optional. Callback with single parameter:
  // last rendered React element from `props.render` or `null` if nothing was rendered yet.
  fallback?: (lastChildren: ReactElement) => ReactElement;
}

Example:

import Resolve from 'react-promise-utils/Resolve';

function Component() {
  const [itemsPromise, setItemsPromise] = React.useState(() => fetchItems());

  return (
    <Resolve
      promise={itemsPromise}
      fallback={lastChildren => <SpinnerOverlay>{lastChildren}</SpinnerOverlay>}
      render={items => <ItemsList items={items} />}
    />
  );
}

Notes:

  • render and fallback should be regular functions, not React elements or components.

usePromiseState

A React hook to keep promises in state. Provides refreshPromise and isCurrent functions.

Example:

import { usePromiseState } from 'react-promise-utils/usePromiseState';

function Component() {
  const [itemsPromise, refreshPromise, isCurrent] = usePromiseState(
    // Provide an async function.
    (offset, limit) => fetch(`/items?offset=${offset}&limit=${limit}`)
      .then(res => res.json()),
    // And optional initial args.
    [0, 20]
  );
  const [selectedId, setSelectedId] = React.useState('');

  React.useEffect(() => {
    itemsPromise.then(items => {
      // Set first item to selected but only if this is the current promise.
      if (isCurrent(itemsPromise)) setSelectedId(items[0].id);
    });
  }, [itemsPromise]);

  return (
    <>
      {/* refeshPromise has the same signature as the provided async function. */}
      <button onClick={() => refreshPromise(0, 20)}>Refresh</button>
      <Items itemsPromise={itemsPromise} selectedId={selectedId} />
    </>
  );
}

Notes:

  • The refreshPromise and isCurrent functions are stable and will never change between renders.
  • Changing the provided async function will not refresh the promise but will change the underlying function refreshPromise calls.

usePromiseDetails

A React hook to inspect the state of a promise (pending, fulfilled, rejected).

Example:

import { PromiseStatus } from 'react-promise-utils/getPromiseDetails';
import { usePromiseDetails } from 'react-promise-utils/usePromiseDetails';

function Component() {
  const [itemsPromise, setItemsPromise] = useState(() => fetchItems());
  const [itemsPromiseStatus, itemsOrError] = usePromiseDetails(itemsPromise);

  if (itemsPromiseStatus === PromiseStatus.PENDING) {
    return <Spinner />;
  }

  if (itemsPromiseStatus === PromiseStatus.REJECTED) {
    return <Error error={itemsOrError} />;
  }

  // PromiseStatus.FULFILLED
  return <ItemsList items={itemsOrError} />;
}

Notes:

  • A promise will always be PENDING the first time it's inspected, even if it has already settled. The status will be updated in the next iteration of the event loop.
  • When a promise state is PENDING, the 2nd item in the tuple is undefined: [PromiseStatus.PENDING, undefined].

getPromiseDetails

A function to read the state of a promise.

Example:

import { getPromiseDetails, PromiseStatus } from 'react-promise-utils/getPromiseDetails';

const itemsPromise = fetchItems();

// Useless example, don't copy this.
const intervalId = window.setInterval(() => {
  const [itemsPromiseStatus, items] = getPromiseDetails(itemsPromise);

  if (itemsPromiseStatus === PromiseStatus.REJECTED) {
    window.clearInterval(intervalId);
  }

  if (itemsPromiseStatus === PromiseStatus.FULFILLED) {
    window.clearInterval(intervalId);
    console.log(items);
  }
}, 200);

Notes:

  • getPromiseDetails has no dependency on React.
  • A promise will always be PENDING the first time it's inspected, even if it has already settled. The status will be updated in the next iteration of the event loop.
  • When a promise state is PENDING, the 2nd item in the tuple is undefined: [PromiseStatus.PENDING, undefined].