0.3.0 • Published 6 years ago

set-future-state v0.3.0

Weekly downloads
81
License
MIT
Repository
github
Last release
6 years ago

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.

0.3.0

6 years ago

0.2.6

6 years ago

0.2.5

6 years ago

0.2.4

6 years ago

0.2.3

6 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.2.0-rc.9

6 years ago

0.2.0-rc.8

6 years ago

0.2.0-rc.7

6 years ago

0.2.0-rc.6

6 years ago

0.2.0-rc.5

6 years ago

0.2.0-rc.4

6 years ago

0.2.0-rc.3

6 years ago

0.2.0-rc.2

6 years ago

0.2.0-rc.1

6 years ago

0.2.0-rc.0

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.3-rc.0

6 years ago

0.0.2-rc.0

6 years ago