vhx / quartz-react

Quartz components using React
2 stars 1 forks source link

Small state manager #27

Closed sebastiansandqvist closed 7 years ago

sebastiansandqvist commented 7 years ago

This PR is a rough draft of a state management library based on the current subscribe/unsubscribe model used in the sidebar.

The gist:

  1. You define a model
const myModel = Model({
  initialState: {
    count: 0
  },
  methods: {
    inc() {
      // whatever is returned in a method gets merged into the state object
      return { count: this.state.count + 1 };
    },
    dec() {
      return { count: this.state.count - 1 };
    },
    // this would be a cool future addition:
    // asyncInc() {
    //   return new Promise((resolve) => {
    //     setTimeout(() => resolve({ count: this.state.count + 1 }) , 2000);
    //   });
    // }
  }
});

/*
myModel looks like this:
  {
    state: { count: 0 },
    inc() { ... },
    dec() { ... },
    subscribe() { ... },
    unsubscribe() { ... }
  }
*/
  1. You connect it to a component:
const Counter = ({ inc, dec, state }) => (
  <div>
    <h1>Count: {state.count}</h1>
    <button onClick={inc}>Increment</button>
    <button onClick={dec}>Decrement</button>
  </div>
);

// all the properties of myModel get passed as props to Counter thanks to connect()
const CounterComponent = connect(myModel, Counter);

The connected component will only update if the underlying state changes, so the more things that are connected the faster react's rendering will be.

The entire implementation is very small: https://github.com/vhx/quartz-react/blob/9d499d3c76684e3abb28ed4a2ec332ed1d552c42/components/util/state-manager.js

The rest of the noise in this PR was to reimplement the sidebar using it.