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 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-async-stateful

v0.13.0

Published

Declarative async state to reduce boilerplate

Readme

react-async-stateful · GitHub license npm version

A consistent method of storing state for async calls to reduce boilerplate in react code

npm i react-async-stateful

Usage

// plain js
import {useAsyncState} from "react-async-stateful";

const AsyncComponent = (props) => {
    const [submitResult, _, updateSubmitResult] = useAsyncState();    

    const submit = useCallback(async () => {
        const {resolvedAt} = await updateSubmitResult(async () => {
            const response = await fetch("https://example.com/api/v1/squeal-loudly");
            return response.json();
        });
        console.log(`API responded at: ${new Date(resolvedAt).toString()}`)
    });
    
    return <div>
        <button onClick={submit}>Call the API!</button>
        {submitResult.resolved && <div>The response: {JSON.stringify(submitResult.value)}</div>}
    </div>;
};

Demos

useAsyncState hook

The useAsyncState hook returns:

    const [asyncState, setAsyncState, updateAsyncState] = useAsyncState(defaultValue);
  • asyncState is the the current value of the async state
  • setAsyncState is usually never needed but can be useful to synchronously update the state, eg:
    import AsyncState from "react-async-stateful";
    
    const updateFromLocalStorage = () => {
      setAsyncState(asyncState => {
          const value = localStorage.getItem("key");
          return AsyncState.resolve(asyncState, value);
      });
    };
  • updateAsyncState is the recommended way of updating. It will automatically update the state and re-render your component with a pending state allowing you to dipslay loading spinners ect.
    const submit = useCallback(() => {
      updateAsyncState(/*promise or an async function*/ async () => {
          const response = await api.get(`user/${userId}`); // thrown errors are automatically handled
          const user = formatUserObject(response.data);
          return user;
      });
    }, [userId]);
    
    // component will receive:
    asyncState.pending === true
    
    // then
    asyncState.resolved === true
    asyncState.value    === user // resolved value
    
    // or if a rejection
    asyncState.rejected === true
    asyncState.error    === Error // error instance

Submit vs Refresh

The default behaviour is that when the updateAsyncState function is called, the current value and errors are wiped and the state is put into an empty pending state.

This can be undesirable if you are merely refreshing data and want to keep the previous value whilst the new request is being made. To fix this you can pass the refresh option so that these are kept:

const refreshList = () => {
    updateList(async () => {
        const response = await api.get("list");
        return response.data;
    }, {refresh: true} /* <-- keep the current value whilst we are pending */);
};

whether submit or refresh were used is stored as submitType on the async state object

The AsyncState object

Note: All operations on async state do not mutate the original object

// typescript
import AsyncState from "react-async-stateful";

// creating the state
const state = AsyncState.create("hello");
console.log(state.pristine); // true
console.log(state.value); // hello

// resolving the state
const resolvedState = AsyncState.resolve(state, "world");
console.log(state.resolved); // true
console.log(state.value); // world

Properties

| key | type | description | --- | --- | --- | defaultValue | T or undefined | default value set at the object creation
| pristine | boolean | have we been updated yet? | pending | boolean | is there an update to the state happening now? | pendingAt | number or null | when the update started | resolved | boolean | do we have a resolved value? if this is true then value must not be undefined | resolvedAt | number or null | when the value the was resolved
| rejected | boolean | if an error occurred or the update was rejected. if this is true then error must not be undefined | rejectedAt | number or null | when the rejection happened 😢 | settled | boolean | if the object is resolved/rejected and not pending | settledAt | number or null | when it was settled | value | T or undefined | the currently resolved value, if undefined we are not resolved
| error | Error or undefined | the reason for the rejection, if undefined we are not rejected
| submitType | AsyncStateSubmitType or undefined | what kind of submit was it? can be either submit or refresh

Typescript Utils

Typescript has a cool feature allowing you to narrow the type of an object using methods. Supplied are some methods that will make null checking your async state objects easier:

import AsyncState, {useAsyncState} from "react-async-stateful";

const [asyncState, _, updateAsyncState] = useAsyncState<UserData>();

runUpdateThatWillHappenInTheFuture();

/* Typescript will complain about the line below 😫 
   Even though our library provides a contract that if resolved is true
   `value` cannot be undefined the typescript compiler has no way of knowing this! */
// return asyncState.resolved ? <div>{asyncState.value.id}</div> : "Loading";

// Use `isResolved` and the compiler will be happy that it is definitely present:
return AsyncState.isResolved(asyncState) ? <div>{asyncState.value.id}</div> : "Loading";

To-Do

  • [ ] tests
  • [ ] better docs
  • [ ] redux actions + reducers