diox/connectors/svelte

Official diox connector for Svelte.

Usage

The useSubscription method allows you to subscribe to changes from a given module, and automatically handles component's reactivity. Returns the transformed 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.

// main.js
// --------------------------

import Counter from './Counter.vue';

new Counter({
  target: document.querySelector('#app'),
});


// 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.svelte
// --------------------------
<script>
import store from './store.js';
import connect from 'diox/connectors/svelte';
const useSubscription = connect(store);

const count = useSubscription('my-module', (newState) => newState.count);

function doSomething() {
  store.dispatch('my-module', 'incrementAsync');
};
</script>

<div @click="doSomething">{$count}</div>

Last updated