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

v2.0.0

Published

A React component and hook render children conditionally based on a promise state

Downloads

149

Readme

react-promiseful

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status

A React component and hook to render children conditionally based on a promise status.

Installation

$ npm install react-promiseful

This library is written in modern JavaScript and is published in both CommonJS and ES module transpiled variants. If you target older browsers please make sure to transpile accordingly.

Demo

You may see a simple demo of react-promiseful in https://moxystudio.github.io/react-promiseful.

Usage

With <PromiseState> component:

import React, { useMemo, useState } from 'react';
import { PromiseState } from 'react-promiseful';

const SomeComponent = (props) => {
    const [savePromise, setSavePromise] = useState();
    const handleSave = useMemo(
        () => () => setSavePromise(props.save()),
        [props.save]
    );

    return (
        <div>
            <button disabled={ saveState.status === 'pending' } onSave={ handleSave }>
                Save
            </button>

            <PromiseState promise={ savePromise }>
                { (saveState) => (
                    <p>
                        { saveState.status === 'pending' && 'Saving...' }
                        { saveState.status === 'fulfilled' && 'Saved!' }
                        { saveState.status === 'rejected' && 'Oops, failed to save' }
                    </p>
                ) }
            </PromiseState>
        </div>
    );
}

With usePromiseState() hook:

import React, { useMemo, useState } from 'react';
import { usePromiseState } from 'react-promiseful';

const SomeComponent = (props) => {
    const [savePromise, setSavePromise] = useState();
    const saveState = usePromiseState(savePromise);
    const handleSave = useMemo(
        () => () => setSavePromise(props.save()),
        [props.save]
    );

    return (
        <div>
             <button disabled={ saveState.status === 'pending' } onSave={ handleSave }>
                Save
            </button>

            <p>
                { saveState.status === 'pending' && 'Saving..' }
                { saveState.status === 'fulfilled' && 'Saved!' }
                { saveState.status === 'rejected' && 'Oops, failed to save' }
            </p>
        </div>
    );
}

API

PromiseState

The <PromiseState> component allows you to conditionally render children based on the promise status and fulfillment/rejection value. It leverages the render props technique to know what to render.

Props

promise

Type: Promise

The promise to observe.

children

A render prop function with the following signature:

(state) => {}

The state argument is an object that contains the following properties:

  • status is one of none (when there's no promise), pending, rejected, fulfilled
  • value is either the fulfillment value or the rejection value
  • withinThreshold indicating if we are still within the configured thresholdMs
thresholdMs

Type: number
Default: 0

The timespan in ms to consider the promise within the threshold. Useful if you want to render a loading only when the promise is taking some time.

The state will contain a withinThreshold boolean property for you to use in the children render prop. Moreover, you may also use "withinThreshold" variants in the statusMap and onSettleDelay props.

statusMap

Type: Object

An object to map statuses, useful when you want to use other names:

{
    pending: 'loading',
    fulfilled: 'success',
    rejected: 'error',
}

When the thresholdMs prop is used, you are also able to map the "withinThreshold" variants. This is useful if you want to hide visual feedback that is too quick. For instance, to avoid having any spinners and success feedback within the threshold:

{
    pendingWithinThreshold: 'none',
    fulfilledWithinThreshold: 'none',
    pending: 'loading',
    fulfilled: 'success',
    rejected: 'error',
}

You may omit statuses you don't want to map and the default ones will be used. Moreover, if no "withinThreshold" statuses are defined, their normal counterparts will be used.

onSettle

Type: Function

A callback to be called whenever the promise fulfills or rejects. It receives the state as argument:

(state) => {}

This is useful to trigger a change in a user-interface after the promise resolves:

const handleSettle = ({ status }) => {
    if (status === 'fulfilled') {
        complete(); // Imaginary function that completes the operation in the UI
    }
};

onSettledDelayMs

Type: number, Object
Default: 0

The delay before calling onSettle. This is useful if you have success animations that must complete before triggering a change in the user-interface.

You may either specify a number to signal the same delay for both fulfilled and rejected statuses or an object containing the granular delays:

{
    fulfilled: 2000,
    rejected: 2000,
}

When the thresholdMs prop is used, you are also able to also map the "withinThreshold" variants. For instance, you may want the callback to be called with a delay, except when there is no visual-feedback:

{
    fulfilledWithinThreshold: 0,
    fulfilled: 2000,
    rejected: 2000,
}

You may omit delays you don't want to map and the default ones will be used. Moreover, if no "withinThreshold" statuses are defined, their normal counterparts will be used.

usePromiseState(promise, [options])

The hook version of the <PromiseState> component. The options available to both are exactly the same.

const promiseState = usePromiseState(somePromise);

The returned value from the hook is the promise state, an object that contains the following properties:

  • status is one of none (when there's no promise), pending, rejected, fulfilled
  • value is either the fulfillment value or the rejection value
  • withinThreshold indicating if we are still within the configured thresholdMs

getPromiseState(promise)

Returns the current promise state, an object with status and value.

If the promise was yet not used in <PromiseState> or usePromiseState(), the promise state will be pending.

Tests

$ npm test
$ npm test -- --watch # during development

License

Released under the MIT License.