react-state-sequencer

0.0.2 • Public • Published

react-state-sequencer

npm build Prettier

react-state-sequencer is a utility library that will let you make updates on your local state in a order.

Internally it uses setState callback and runs each update inside callback of previous setState call. The behavior then is an escape hatch to react setState calls batching. An example:

import React from "react";
import updateState from "react-state-sequencer";
 
class App extends React.Component {
  state = {
    counter: 1
  };
 
  handleButtonClick = () => {
    updateState(
      { counter: 1 },
      { counter: 2 },
      prevState => ({ counter: prevState.counter + 1 })
    )(this);
  };
 
  render() {
    console.log(this.state.counter);
    return (
      <div>
        <button onClick={this.handleButtonClick}>update state</button>
        <h2>{this.state.counter}</h2>
      </div>
    );
  }
}

Result of console.log:

1 2 3

You can also pass a function that returns a Promise as an argument

The following example will print 1, 2, 3 every second:

import React from "react";
import updateState from "react-state-sequencer";
 
const delayBySecond = () =>
  new Promise(resolve => {
    setTimeout(() => resolve(), 1000);
  });
 
class App extends React.Component {
  state = {
    counter: 1
  };
 
  countToThree = () => {
    updateState(
      { counter: 1 },
      delayBySecond,
      { counter: 2 },
      delayBySecond,
      { counter: 3 }
    )(this);
  };
 
  render() {
    return (
      <div>
        <button onClick={this.countToThree}>count to three</button>
        <h2>{this.state.counter}</h2>
      </div>
    );
  }
}

Warning

Be careful when using Promises. You may run into the following error:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

This happens when the component gets unmounted before the Promise resolves (e.g. when a user changes the route). Some function holds a reference to a "dead" component and tries to update it. This should be avoided.

Why?

Because I love local state (Yes, that's my chance to express that I like to keep things local unless there is a clear benefit of doing the opposite). Other than that it's just an experimental idea that popped to my head after I had to first unmount a children component before changing a number of a controlled tab (if not I would get a DOM exception).

Package Sidebar

Install

npm i react-state-sequencer

Weekly Downloads

6

Version

0.0.2

License

ISC

Unpacked Size

8.85 kB

Total Files

9

Last publish

Collaborators

  • tomekmularczyk