Listen on state changes

To listen on state changes, you need to attach a "hook" in the store using the hook method. The hook will trigger depending on what action query you passed in it.

To see that in action, here is the simple example of a hook that queries the actions INCREMENT_COUNT and DECREMENT_COUNT.

your-controller.js
import { CounterStore } from 'counter-store';

function YourController($scope, counterStore) {
  counterStore.hook('INCREMENT_COUNT', (state) => {
    $scope.count = state.count;
  });

  counterStore.hook('DECREMENT_COUNT', ({ count }) => {
    $scope.count = count;
  });
}

angular
  .module('App', [])
  .controller('YourController', YourController);

To check if the hook callback is currently running on its initial phase, you can use the second argument from the callback function which determines if it is an initial phase.

As you can notice in the first example, you update the same scope variable (which is the count) using two different hooks that listen on INCREMENT_COUNT and DECREMENT_COUNT, you can simplify that by using a wild card, array, or regular expression action query.

your-controller.js
import { CounterStore } from 'counter-store';

function YourController($scope, counterStore) {
  // Using an array of action
  counterStore.hook(['INCREMENT_COUNT', 'DECREMENT_COUNT'], (state) => {
    $scope.count = state.count;
  });
  
  // Using a wild card
  counterStore.hook('*', (state) => {
    $scope.count = state.count;
  });
  
  // Using a regular expression
  counterStore.hook(/^(IN|DE)CREMENT_COUNT$/, (state) => {
    $scope.count = state.count;
  });
}

angular
  .module('App', [])
  .controller('YourController', YourController);

Last updated

Was this helpful?