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-switch

v2.0.0-beta.1

Published

Easily handle promises in your React components.

Downloads

801

Readme

React Promise Switch · GitHub license npm version flow coverage code style: prettier

React Promise Switch abstracts the overhead and complexity of using promises to store and render data in a component's state.

Example

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

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

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

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

    return <UsersList users={users} />;
}

Usage

usePromiseSwitch accepts a function that returns a promise and an optional object of options:

usePromiseSwitch(fn, options)

fn

Type: <T>() => Promise<T>

A function that returns a promise. When fn's reference changes, usePromise will cancel the old request and start the new one.

Examples

const getUsers = () => Promise.resolve([{ id: 1, name: "Adam" }]);

function UsersList() {
    const [err, users] = usePromise(getUsers);
    
    return <pre>{users ? JSON.stringify(users, null, 2) : null}</pre>;
}

If you define fn inside of a React component, make sure to memoize the function so its reference doesn't change on re-render:

function UsersList() {
    const [err, users] = usePromise(React.useCallback(() => axios.get("/users"), []));
    
    return <pre>{users ? JSON.stringify(users, null, 2) : null}</pre>;
}

Options

mode

Type: "latest" | "every"
Default: "latest"

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.

cancel

Type: ?(Promise) => void
Default: void

Although usePromise will cancel any provided promise out of the box, it can be helpful to integrate cancelation more deeply when using libraries like Bluebird or 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-promise-switch";

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} />
}