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

set-future-state

v0.3.0

Published

Safely setState in the future

Downloads

7

Readme

setFutureState

npm version Build Status Greenkeeper badge

npm install --save set-future-state
# or
yarn add set-future-state

The Problem

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

In React, calling this.setState() in an async function, or in the .then() method of a Promise, is very common and very useful. But if your component is unmounted before your async/promise resolves, you’ll get the above error in your console. The React blog suggests using cancelable Promises, but as Aldwin Vlasblom explains:

Because Promises were designed to have no control over the computation and make their values accessible to any number of consumers, it makes little sense, and turns out to be quite a challenge, to implement cancellation.

Enter Futures.

The Solution

This library has a single default export: the function withFutureState().

type SetFutureState<P, S> = <E, V>(
  self: Component<P, S>,
  eventual: Future<E, V> | (() => Promise<V>),
  reducer: (value?: V, prevState: S, props: P) => $Shape<S> | null,
  onError?: (error: E) => *
) => void

declare export default function withFutureState<P, S>(
  factory: (setFutureState: SetFutureState<P, S>) => Class<Component<P, S>>
): Class<Component<P, S>>

Usage

withFutureState() is an Inheritance Inversion Higher-Order Component. It takes a single argument, a factory function, which must return a React Class Component (i.e. a class that inherits from React.Component or React.PureComponent). The factory function receives a single argument, setFutureState: your tool for safely updating your component's state in the future.

import React, {Component} from 'react'
import withFutureState from 'set-future-state'

export default withFutureState(
  setFutureState =>
    class MyComponent extends Component {
      state = {
        loading: true,
        fetchCount: 0,
        data: null,
      }

      componentDidMount() {
        setFutureState(
          this,
          () => fetch('https://www.example.com'),
          (data, prevState, props) => ({
            data,
            loading: false,
            fetchCount: prevState.fetchCount + 1,
          }),
          error => console.error(error)
        )
      }

      render() {
        return this.state.loading ? (
          <p>Loading . . .</p>
        ) : (
          <p>{JSON.stringify(this.state.data)}</p>
        )
      }
    }
)

setFutureState() takes the following 4 arguments:

  • self (required)

    Pass this as the first argument, so that setFutureState() can update your component's state.

  • eventual (required)

    The second argument should be either:

    • a function that returns a Promise. When it resolves, the resolved value will be passed to the reducer.
    • a Future.
  • reducer (required)

    The third argument should be a function that takes 3 arguments, and returns your updated state. It is called when your eventual resolves. It works exactly like the function form of setState: return a partial state object, and it will merge it into your existing state; return null, and it will do nothing. The arguments passed to reducer are:

    • value: the resolved value from your eventual (Promise or Future)
    • prevState: your component's existing state
    • props: your component's props
  • onError (optional)

    The fourth and final argument is optional: a function that is called if the eventual (Promise or Future) rejects. It is called with the rejection reason (ideally an Error object).

IMPORTANT: If you leave out onError, your reducer will be called if the eventual resolves AND if it rejects. This is useful, for example, to remove loading spinners when an ajax call completes, whether or not it was successful.

Browser Support

setFutureState is transpiled with Babel, to support all browsers that ship native WeakMap support. You can see a list of compatible browser versions on MDN.