diox/connectors/react

Official diox connector for React.

Usage

The useSubscription method allows you to subscribe to changes from a given module, and automatically handles component's reactivity. Returns the reduced state each time it changes.

useSubscription(moduleId: string, reducer?: (newState: any) => any): any
  • moduleId Id of the module to subscribe to.

  • reducer Optional state reducer. Allows you to transform the new state to get exactly what you need. Defaults to the identify function.

Diox connector for React relies on the concept of hooks.

// main.jsx
// --------------------------
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Counter from './Counter.jsx';

ReactDOM.render(<Counter />, document.body);


// store.js
// --------------------------
import { Store } from 'diox';

const store = new Store();
store.register('my-module', {
  state: {
    count: 0,
  },
  mutations: {
    INCREMENT: ({ state }) => {
      return state.count + 1;
    },
  },
  actions: {
    incrementAsync: ({ mutate, id }) => {
      setTimeout(() => {
        mutate(id, 'INCREMENT');
      }, 250);
    },
  },
});

export default store;


// Counter.jsx
// --------------------------
import * as React from 'react';
import store from './store.jsx';
import connect from 'diox/connectors/react';

const useSubscription = connect(store);

export default function Button(props) {
  const count = useSubscription('my-module', (newState) => newState.count);
  const doSomething = () => {
    store.dispatch('my-module', 'incrementAsync');
  };
  return <button type="button" onClick={doSomething}>{count}</button>;
}

Last updated