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

v1.0.2

Published

React Higher-Order Component to handle promise cancelation when the component unmounts

Downloads

13

Readme

React Cancelable

React Higher-Order Component to handle promise cancelation when the component unmounts.

React Cancelable is a Higher-Order Component that wraps handlers into new functions that return a Cancelable, which are safely canceled when the component unmounts.

Status

Travis Greenkeeper badge

Installation

npm install react-promise-cancelable promise-cancelable --save
yarn add react-promise-cancelable promise-cancelable

API

cancelable()

cancelable(
  propsMapper: (ownerProps: Object) => Object
): HigherOrderComponent

Accepts a function that maps owner props to a new collection of props that are passed to the base component. The remapped props are wrapped functions around a new Cancelable that are safely canceled when the component unmounts.

Note: Every handlers that are not functions are therefore ignored.

Usage

Basic example

One of the use cases is to avoid calling setState() after a component has unmounted. The Higher-Order Component keeps a list of registered cancelables and calls the Cancelable.cancel() method for each registered cancelable.

// ./delay.js
import Cancelable from 'promise-cancelable';

export default delta =>
  new Cancelable((resolve, reject, onCancel) => {
    const id = setTimeout(() => {
      resolve(id);
    }, delta);

    onCancel(() => {
      clearTimeout(id);
    });
  });
// ./my-component.js
import React, { Component } from 'react';
import delay from './delay';
import cancelable from 'react-promise-cancelable';

class MyComponent extends Component {
  state = { value: 'Not called' };

  updateValue = () => {
    // When the component unmounts the cancelable returned by `delay` is
    // canceled, so the `setState` method is not called.
    this.cancelable = this.props.delay(1000).then(() => {
      this.setState({ value: 'Called!' })
    });
  }

  cancel = () => {
    if (this.cancelable) {
      // Stop the progress of an ongoing asynchronous task.
      this.cancelable.cancel();
    }
  }

  render() {
    return (
      <div>
        <div>
          {this.state.value}
        </div>

        <button onClick={this.updateValue}>
          {'Click!'}
        </button>

        <button onClick={this.cancel}>
          {'Cancel!'}
        </button>
      </div>
    );
  }
}

export default cancelable(() => ({ delay }))(MyComponent);

Canceling a HTTP request

Some HTTP clients provide a way to cancel requests. axios has a cancellation API using a cancel token.

We can create a new instance of axios and patch its methods in order to make them cancelable.

//./axios.js
import Cancelable from 'promise-cancelable';
import axios from 'axios';

const makeCancelableRequest = method => (...args) => {
  return new Cancelable((resolve, reject, onCancel) => {
    const { CancelToken } = axios;
    // Create a cancellation token every time the method is called. This way we
    // avoid creating global tokens that could cancel all the subscribed requests.
    const source = CancelToken.source();

    // We create a new instance internally to avoid polluting the global
    // instance defaults.
    const instance = axios.create();

    instance.defaults.cancelToken = source.token;

    instance
      [method](...args)
      .then(result => {
        resolve(result);
      })
      .catch(reason => {
        // Check whether the reason is a cancellation notification.
        if (!axios.isCancel(reason)) {
          reject(reason);
        }
      });

    onCancel(() => {
      source.cancel();
    });
  });
};

const instance = axios.create();

// Example with `get`.
instance.get = makeCancelableRequest('get');

export default instance;

Now we can import our own axios instance and use it to create new requests that can be easily canceled whether when the user navigates to another page or by explicitly calling the cancel() method of that subscription.

// ./app.js
import axios from './axios';

class App extends Component {
  state = { loading: false };

  getUsers = () => {
    if (this.cancelable) {
      // Cancel the previous request.
      this.cancelable.cancel();
    }

    // Show an initial loader.
    this.setState({ loading: true });

     // When the component unmounts this request will be canceled.
    this.cancelable = this.props.getUsers().then(() => {
      this.setState({ loading: false });
    }, () => {
      this.setState({ loading: false });
    });
  }

  render() {
    return (
      <div>
        {this.state.loading ? <Loader /> : null}

        <button onClick={this.getUsers}>{'Get users!'}</button>
      </div>
    );
  }
}

export default cancelable(() => ({
  getUsers: () => axios.get('/users')
}))(App);

Related

Cancelable

Licence

MIT © João Granado