Git Product home page Git Product logo

set-future-state's Introduction

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().

withFutureState() type signature (in flow notation)
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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.