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-smart-promise

v1.0.4

Published

Easily handle promises in your React components

Downloads

1,188

Readme

Hook for dealing with promises in React components

GitHub license npm version code style: prettier typescript coverage bundle size

Try the other libaries in the series! React Stateful Tabs, React Use Pagination, React Accessible Form

✨ Features

  • 📦 Works with any code or library that uses promises
  • 🌬 Customizable cancelation for libraries like Axios and native fetch
  • 🎯 Complete TypeScript generics for automatic inference of promise result type
  • 🔄 Multiple re-fetch modes (every, latest) for scenarios like typeahead search or debounced inputs
  • ⚡️ Fully customizable for pagination, optimistic updates, infinite scroll, polling, etc.
  • 🐜 Tiny yet powerful — less than 1kb gzipped

Example

import axios from "axios";
import { usePromise } from "react-smart-promise";

const fetchUsers = () => axios.get("/users");

function App() {
    const [err, users, status] = usePromise(fetchUsers);

    if (err) {
      return "Error fetching users.";
    }
    
    if (!users) {
        return "Loading...";
    }

    return <ul>
      {users.map(user => <li>{user.name}</li>)}
    </ul>;
}

API

const [error, data, status] = usePromise(options);

options

{
  mode?: "latest" | "every", // (default: "latest")
  onCancel?: (promise: Promise<T>) => void, // (default: void)
}

mode

Determines whether to show only the most recent promise (latest) or to show the most recently resolved promise in the queue (every). A typical usecase for every is when implementing an “auto-complete” search, where you want to show the latest result as they stream in.

onCancel

Although usePromise will cancel the promise out of the box, it can be helpful to integrate cancelation more deeply when using libraries like Axios. The function you provide will be called whenever usePromise determines cancelation is needed (such as during unmount, changing the promise before the first one has completed, etc.)

Example (Axios)

You need a way to reference the cancel function from Axios's CancelToken. One common way to approach this is to add a .cancel method to the promise returned by Axios:

import Axios, { CancelToken } from "axios";

const getUsers = () => {
    const source = CancelToken.source();
    const promise = axios.get("/users", { cancelToken: source.token }).then(res => res.data);
    promise.cancel = () => source.cancel();
    return promise;
}

You can then call it in the cancel option for usePromise:

usePromise(getUsers, {
    cancel: promise => promise.cancel();
});

If you wrap all of your Axios promises this way and often use usePromise throughout your app, it can be helpful to preconfigure this option:

import { usePromise } from "react-smart-promise";

export const useAxiosPromise = (fn, options) => usePromise(fn, { 
    cancel: axiosPromise => axiosPromise.cancel(), 
    ...options 
});

More Examples

Waiting to Fetch Data

Sometimes you don't want to trigger the promise right away, but instead want to wait until some action has occurred. You can pass null to usePromise and it will remain in the "INITIAL" state:

const submitData = () => axios.post("/register", { id: 1 });

function App() {
    const [submitted, setSubmitted] = React.useState(false);
    const [err, result, status] = usePromise(submitted ? submitData : null);

    return <button onClick={() => setSubmitted(true)} disabled={STATUS === "PENDING"}>Submit</button>;
}

Providing Arguments

Sometimes you may want to pass arguments to the function provided to usePromise. You should wrap the function call with a React.useCallback so that it only re-fetches when the arguments change.

const getUser = (id) => axios.get("/users", {id});

function SelectUser() {
    const [userId, setUserId] = React.useState("1");
    const [err, user] = usePromise(React.useCallback(() => getUser(userId), [userId]))
    
    return (
        <div>
            <UserSelector id={userId} onChange={setUserId} />
            <UserProfile user={user} />;
        </div>
    );
}

Handling Side Effects

If you need to handle side effects after the state of the promise changes, you can use React.useEffect.

const submitForm = (formState) => axios.post("/submit", formState);

function FormContainer() {
    const [submitted, setSubmitted] = React.useState(false);
    const [formState, setFormState] = React.useState({});
    const [formErrors, successful, status] = usePromise(submitted ? React.useCallback(() => submitForm(formState), [formState]) : null);
    
    React.useEffect(() => {
        if (successful) {
            window.location = "/";
        }
    }, [successful]);
    
    return <Form value={formState} onChange={setFormState} onSubmit={() => setSubmitted(true)} errors={formErrors} />
}