react-promise-switch

Easily handle promises in your React components.


Keywords
react, promise, data, fetch, loading, ajax, rest, state
License
MIT
Install
npm install react-promise-switch@2.0.0-beta.1

Documentation

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