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.

set-future-state's People

Contributors

benadamstyles avatar greenkeeper[bot] avatar

Watchers

 avatar  avatar

set-future-state's Issues

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml
  • The new Node.js version is in-range for the engines in 1 of your package.json files, so that was left alone

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepoundefined

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v16.5.1

16.5.1 (September 13, 2018)

React

  • Improve the warning when React.forwardRef receives an unexpected number of arguments. (@andresroberto in #13636)

React DOM

  • Fix a regression in unstable exports used by React Native Web. (@aweary in #13598)
  • Fix a crash when component defines a method called isReactComponent. (@gaearon in #13608)
  • Fix a crash in development mode in IE9 when printing a warning. (@link-alex in #13620)
  • Provide a better error message when running react-dom/profiling with schedule/tracking. (@bvaughn in #13605)
  • If a ForwardRef component defines a displayName, use it in warnings. (@probablyup in #13615)

Schedule (Experimental)

  • Add a separate profiling entry point at schedule/tracking-profiling. (@bvaughn in #13605)
FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of eslint-plugin-babel is breaking the build 🚨

The devDependency eslint-plugin-babel was updated from 5.2.0 to 5.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-babel is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 2 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of eslint-plugin-eslint-comments is breaking the build 🚨

The devDependency eslint-plugin-eslint-comments was updated from 3.1.0 to 3.1.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-eslint-comments is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v3.1.1

🐛 Bug Fixes

  • 3cd7256 reverted the autofix of eslint-comments/no-unused-disable rule because of some problems (#21 (comment)).
Commits

The new version differs by 3 commits.

  • cc1a193 🔖 3.1.1
  • 3cd7256 Revert "Update: make no-unused-disable fixable (#13)"
  • 0edf03c ⬆️ update vuepress

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of eslint-plugin-jest is breaking the build 🚨

The devDependency eslint-plugin-jest was updated from 21.27.1 to 21.27.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v21.27.2

21.27.2 (2018-11-06)

Bug Fixes

  • valid-expect-in-promise: fix type exception (60919f6), closes #195
Commits

The new version differs by 1 commits.

  • 60919f6 fix(valid-expect-in-promise): fix type exception

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.