Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Store<T, U>

State management implementation based on the vuex API.

Creating a store instance

There are two methods for creating a store instance.

You can use the new operator with the class or use the static create method.

The create method only has to be used in a typescript environment to get proper type support on the created store instance.

const store = new Store(options);

// Provides correct type support in a typescript environment
const store = Store.create(options);

Options

State

State is a data object that is observed for data changes.

const store = new Store({
  state: {
    price: 20,
    quantity: 10,
    // Computed property that evaluates to the result of calling the function.
    // They automatically update when their dependencies update so that they always contain the latest value.
    // For example changing either price, qty or both will cause total to be reevaluated.
    total(): number {
      return this.price * this.quantity;
    }
  }
});

 console.log(store.$state); // output: { price: 20, quantity: 10, total: 200 }

 // Store state is protected and cannot be set directly, use mutations to change store state.
 store.$state.price = 50; // This line will throw an exception.

Mutations

Mutations are synchronous functions that can be used change store state.

Asynchronous data changes in a mutation will cause an error to occur. If you need to run some workflow that updates store state use a combination of actions and mutations.

  const store = new Store({
    state: {
      price: 20,
      quantity: 10,
      total(): number {
        return this.price * this.quantity;
      }
    },
    mutations: {
      // All mutations receive a context variable as a first parameter which has been destructured in the following example.
      // The second parameter is the payload passed to the mutation which can be any value.
      // Use payload as an object if you wish to pass multiple parameters to the mutation.
      incrementPriceBy({ $state, $commit }, value){
        $state.price += value;

        // You can do another commit from this mutation.
        $commit('SOME_OTHER_COMMIT', value);

        // Mutations can return a result to the caller.
        return true;
      }
  }});

 const success = store.$commit('incrementPriceBy', 20);
 console.log(success); // output: true
 console.log(store.$state); // output: { price: 40, quantity: 10, total: 400 }

Actions

Actions are pieces of functionality, often asynchronous, that performs a set of operations or executes a workflow.

They cannot modify store state directly and should instead use the context.commit parameter to persist data changes.

  const store = new Store({
    state: {
      price: 20,
      quantity: 10,
      total(): number {
        return this.price * this.quantity;
      }
    },
    mutations: {
      ...
    }
    actions: {
      // All actions receive a context variable as a first parameter which has been destructured in the following example.
      // The second parameter is the payload passed to the action which can be any value.
      // Use payload as an object if you wish to pass multiple parameters to the action.
      setTotal({ $state, $commit, $dispatch }, payload) {
        // State in actions are readonly and will cause an error when you try to change a value.
        $state.price = 50; // this line throws an exception

        // Do some stuff probably asynchronously

        // To change state you can use context.commit which is a proxy for <a href="_store_store_.store.html#_commit">$commit</a>.
        $commit('setPrice', payload.price);
        $commit('setQty', payload.qty);

        // You can also call other actions using context.dispatch which is a proxy for <a href="_store_store_.store.html#_dispatch">$dispatch</a>.
        $dispatch('SOME_OTHER_ACTION', 'SOME_OTHER_PAYLOAD');

        // Actions can return a value to the caller
        return 55;
      }
      doSomethingAsync({ $state, $commit, $dispatch }, payload) {
        // You use promises with actions by returning a Promise
        return new Promise((resolve, reject) => {
          try {
            // Do something

            resolve();
          }
          catch(error) {
            reject(error);
          }
        });
      }
    }
  });

 const result = store.$dispatch('setTotal', { price: 50, qty: 30 });
 // Ignoring the line that causes an error in the action this would be the output
 console.log(result); // output: 55
 console.log(store.$state); // output: { price: 50, quantity: 30, total: 1500 }

 // Example of using promise based actions
 store.$dispatch('doSomethingAsync', 'value').then(value => {
   // Do something after promise completes with the resolved value.
 });

Modules

Modules are a way to define recursive store instances nested under the root store instance.

 const store = Store.create({
   state: {
     owner: 'owner'
   },
   mutations: {},
   actions: {},
   modules: {
     factory: {
       state: {
         workers: [],
         headCount(): number {
           return this.workers.length;
         },
       },
       actions: {
         addWorker({ state }, payload) {
           // Add a worker
         },
       },
       modules: {
         shop: {
           state: {
             employees: [],
             manager: 'someone',
             headCount(): number {
               return this.employees.length + 1;
             },
           },
         },
       },
     },
   }
 });

// The following shows how you would use the store instances created from these module definitions.

 store.$state.owner;
 store.$commit('MUTATION_NAME', '');
 store.$dispatch('ACTION_NAME', {});

 store.factory.$state.headCount;
 store.factory.$commit('MUTATION_NAME', {});
 store.factory.$dispatch('ACTION_NAME', '');

 store.factory.shop.$state.employees;
 store.factory.shop.$commit('MUTATION_NAME', []);
 store.factory.shop.$dispatch('ACTION_NAME', []);

Type parameters

Hierarchy

  • Store

Index

Constructors

constructor

Properties

Private Readonly $actions

Map of actions that can get invoked using $dispatch.

Private Readonly $mutations

Map of mutations that can get invoked using $commit.

Readonly $state

$state: ObservedData<T>

Store instance data.

Methods

$commit

  • $commit<U>(mutation: string, payload?: U): void
  • Calls a store Store.$mutations mutation passing in the data the it needs to perform its task.

    Type parameters

    • U

      Any valid javascript type.

    Parameters

    • mutation: string

      Name of the mutation to call.

    • Optional payload: U

      Value to pass to the mutation.

    Returns void

$dispatch

  • $dispatch<U>(action: string, payload?: U): any
  • Calls a store Store.$actions action passing in the data the it needs to perform its task.

    Type parameters

    • U

      Any valid javascript type.

    Parameters

    • action: string

      Name of the action to call.

    • Optional payload: U

      Value to pass to the action.

    Returns any

$unwatch

  • Stop a function from executing when a $state property changes.

    Type parameters

    • U

    Parameters

    • propertyPath: string

      Path to the property on $state, if nested use the dot operator for ex nested.property.

    • watcher: WatcherFunction<U>

      Function to be removed when the property at propertyPath changes.

    Returns void

$watch

  • Add a function to be executed when a $state property changes.

    Type parameters

    • U

    Parameters

    • propertyPath: string

      Path to the property on $state, if nested use the dot operator for ex nested.property.

    • watcher: WatcherFunction<U>

      Function to be called when the property at propertyPath changes.

    Returns WatcherFunction<U>

Static create

Generated using TypeDoc