1.0.2 • Published 6 years ago

react-stater v1.0.2

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

React Stater

Simple state handler for react, which make it easy to share states between components.

Installation

yarn add react-stater

or

npm install react-stater

Example

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Stater, { applyStaters } from 'react-stater';

class CounterState extends Stater {
  counter = 0;

  increment = () => {
    this.counter++;
    this.render(); // Comes from Stater class
  };

  decrement = () => {
    this.counter--;
    this.render(); // Comes from Stater class
  };
}

const counterState = new CounterState();

class CounterComponent extends Component {
  render() {
    const { counter, increment, decrement } = this.props.counterState;
    return (
      <div>
        {counter}
        <button onClick={increment}>Icrement</button>
        <button onClick={decrement}>Decrement</button>
      </div>
    );
  }
}

const CounterComponentWithStateApplied = applyStaters(CounterComponent, {
  counterState,
});

ReactDOM.render(
  <CounterComponentWithStateApplied />,
  document.getElementById('app')
);

Stater

The Stater class has private list of components (which is applied by applyStaters and we dont really have to care about.) and a method named render. render method loops through all components and runs forceUpdate on them, which will force the HOC's to render and then apply the new props.

The render method should be applied everytime you have updated the state and want to tell the components about it.

It could be use several times. e.g. in a async method to tell the components it is loading, and then when done, tell them the loading is complete has new data.

class CounterState extends Stater {
  counter = 0;

  increment = () => {
    this.counter++;
    this.render(); // Comes from Stater class
  };

  decrement = () => {
    this.counter--;
    this.render(); // Comes from Stater class
  };
}

applyStaters

applyStaters is HOC-function which add itself as component in every applied staters components list. That way it know which components to rerender.

Simplest way of passing the states to the props:

const CounterComponentWithStateApplied = applyStaters(CounterComponent, {
  counterState,
});

Passing several states to the props:

const CounterComponentWithStateApplied = applyStaters(CounterComponent, {
  counterState,
  someOtherStateClass,
  andSomeOtherStateClass,
});

HOC-funciton also have an optional param. Which takes a function where you can apply only that you actually need, or maybe rename them. e.g.

const CounterComponentWithStateApplied = applyStaters(
  CounterComponent,
  { counterState },
  state => {
    return {
      theCounter: state.counterState.counter,
      icrement: state.counterState.increment,
    };
  }
);
1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago