AngularJS Store
v4.0.5
v4.0.5
  • Introduction
  • What's New
  • Installation
  • Tutorials with Javascript
    • Setup a store
    • Get the current state
    • Update the state
    • Listen on state changes
    • Destroy a hook
  • Tutorials with Typescript
    • Setup a store
    • Get the current state
    • Update the state
    • Listen on state changes
    • Destroy a hook
Powered by GitBook
On this page

Was this helpful?

  1. Tutorials with Javascript

Update the state

In AngularJS Store, the only way to update the state from the store is by dispatching an action. By using the dispatch method, you're also able to notify some parts of your application that uses the same store.

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

function YourController(counterStore) {
  let currentState;

  currentState = counterStore.copy();
  counterStore.dispatch('INCREMENT_COUNT', {
    count: currentState.count + 1;
  });

  currentState = counterStore.copy();
  counterStore.dispatch('DECREMENT_COUNT', {
    count: currentState.count - 1;
  });
}

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

As you can notice in the above example, every time you perform an update to the state, you get the current state first because you used it for computation.

dispatch method has a simple way for that scenario that you can use.

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

function YourController(counterStore) {
  counterStore.dispatch('INCREMENT_COUNT', (currentState) => {
    return { count: currentState.count + 1 };
  });

  counterStore.dispatch('DECREMENT_COUNT', (currentState) => {
    return { count: currentState.count - 1 };
  });
}

angular
  .module('App', [])
  .controller('YourController', YourController);
PreviousGet the current stateNextListen on state changes

Last updated 5 years ago

Was this helpful?