Introduction

Dojo stores provide a predictable, consistent state container with built-in support for common state management patterns.

The Dojo stores package provides a centralized store designed to be the single source of truth for an application. Dojo applications operate using uni-directional data flow; as a result, all application data follows the same lifecycle, ensuring the application logic is predictable and easy to understand.

FeatureDescription
Global data storeApplication state gets stored globally in a single source of truth.
Uni-directional data flowPredictable and global application state management.
Type-safeAccess and modification of state gets protected by interfaces.
Operation-driven state changesEncapsulated, well-defined state modifications that can be recorded, undone and replayed.
Asynchronous supportAsync commands supported out-of-the-box.
Operational middlewareBefore and after operations, error handling, and data transformation.
Simple widget integrationTools and patterns for easy integration with Dojo widgets.

Basic usage

Dojo provides a reactive architecture concerned with constantly modifying and rendering the current state of an application. In simple systems this can happen at a local level and widgets can maintain their own state. However, as a system becomes more complex the need to better compartmentalize and encapsulate data and create a clean separation of concerns quickly grows.

Stores provide a clean interface for storing, modifying, and retrieving data from a global object through unidirectional data flow. Stores include support for common patterns such as asynchronous data retrieval, middleware, and undo. Stores and their patterns allow widgets to focus on their primary role of providing a visual representation of information and listening for user interactions.

The store

The store holds the global, atomic state for the entire application. The store should be created when the application gets created and defined in the Registry with an injector.

main.ts

  1. import { registerStoreInjector } from '@dojo/framework/stores/StoreInjector';
  2. import Store from '@dojo/framework/stores/Store';
  3. import { State } from './interfaces';
  4. const store = new Store<State>();
  5. const registry = registerStoreInjector(store);

State defines the structure of the global store using an interface. Everything inside State should be serializable, i.e. convertible to/from JSON, as this improves performance by making it easier for the Dojo virtual DOM system to determine when changes to the data occur.

interfaces.d.ts

  1. interface User {
  2. id: string;
  3. name: string;
  4. }
  5. export interface State {
  6. auth: {
  7. token: string;
  8. };
  9. users: {
  10. current: User;
  11. list: User[];
  12. };
  13. }

The above is a simple example that defines the structure for the store used in the rest of the examples in this guide.

Updating stores

There are three core concepts when working with Dojo stores.

  • Operations - instructions to manipulate the state held by the store
  • Commands - simple functions that perform business logic and return operations
  • Processes - execute a group of commands and represent application behavior

Commands and operations

To modify a store, when executing a process, a command function gets invoked. The command function returns a list of operations to apply to the store.. Each command is passed a CommandRequest which provides path and at functions to generate Paths in a type-safe way, a get function for access to the store’s state, a payload object for the argument that the process executor was called with.

Command factory

Stores have a simple wrapper function that acts as a type-safe factory for creating new commands.

To create a store factory:

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. const createCommand = createCommandFactory<State>();
  4. const myCommand = createCommand(({ at, get, path, payload, state }) => {
  5. return [];
  6. });

createCommand ensures that the wrapped command has the correct typing and the passed CommandRequest functions get typed to the State interface provided to createCommandFactory. While it is possible to manually type commands, the examples in this guide use createCommand.

path

The path is a string that describes the location where an operation gets applied. The path function is part of the CommandRequest and is accessible inside of a Command.

In this example the path describes a location in the store. The State is the same as defined above in interface.d.ts. The State interface gets used by the Store to understand the shape of the state data.

To define a path for the current user name:

  1. const store = new Store<State>();
  2. const { path } = store;
  3. path('users', 'current', 'name');

This path refers to the string value located at /users/current/name. path gets used to transverse the hierarchy in a type-safe way, ensuring that only the property names defined in the State interface get used.

at

The at function gets used in conjunction with path to identify a location in an array. This example leverages the at function.

  1. const store = new Store<State>();
  2. const { at, path } = store;
  3. at(path('users', 'list'), 1);

This path refers to the User located at /users/list at offset 1.

add operation

Adds a value to an object or inserts it into an array.

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. import { add } from '@dojo/framework/stores/state/operations';
  4. const createCommand = createCommandFactory<State>();
  5. const myCommand = createCommand(({ at, get, path, payload, state }) => {
  6. const user = { id: '0', name: 'Paul' };
  7. return [add(at(path('users', 'list'), 0), user)];
  8. });

This adds user to the beginning of the user list.

remove operation

Removes a value from an object or an array.

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. import { add, remove } from '@dojo/framework/stores/state/operations';
  4. const createCommand = createCommandFactory<State>();
  5. const myCommand = createCommand(({ at, get, path, payload, state }) => {
  6. const user = { id: '0', name: 'Paul' };
  7. return [
  8. add(path('users'), {
  9. current: user,
  10. list: [user]
  11. }),
  12. remove(at(path('users', 'list'), 0))
  13. ];
  14. });

This example adds an initial state for users and removes the first user in the list.

replace operation

Replaces a value. Equivalent to a remove followed by an add.

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. import { add, replace } from '@dojo/framework/stores/state/operations';
  4. const createCommand = createCommandFactory<State>();
  5. const myCommand = createCommand(({ at, get, path, payload, state }) => {
  6. const users = [{ id: '0', name: 'Paul' }, { id: '1', name: 'Michael' }];
  7. const newUser = { id: '2', name: 'Shannon' };
  8. return [
  9. add(path('users'), {
  10. current: user[0],
  11. list: users
  12. }),
  13. replace(at(path('users', 'list'), 1), newUser)
  14. ];
  15. });

This example replaces the second user in the list with newUser.

get

The get function returns a value from the store at a specified path or undefined if a value does not exist at that location.

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. import { remove, replace } from '@dojo/framework/stores/state/operations';
  4. const createCommand = createCommandFactory<State>();
  5. const updateCurrentUser = createCommand(async ({ at, get, path }) => {
  6. const token = get(path('auth', 'token'));
  7. if (!token) {
  8. return [remove(path('users', 'current'))];
  9. } else {
  10. const user = await fetchCurrentUser(token);
  11. return [replace(path('users', 'current'), user)];
  12. }
  13. });

This example checks for the presence of an authentication token and works to update the current user information.

payload

The payload is an object literal passed into a command when it is called from a process. The payload‘s type may be defined when constructing the command.

  1. import { createCommandFactory } from '@dojo/framework/stores/process';
  2. import { State } from './interfaces';
  3. import { remove, replace } from '@dojo/framework/stores/state/operations';
  4. const createCommand = createCommandFactory<State>();
  5. const addUser = createCommand<User>(({ at, path, payload }) => {
  6. return [add(at(path('users', 'list'), 0), payload)];
  7. });

This example adds the user provided in the payload to the beginning of /users/list.

Asynchronous commands

Commands can be synchronous or asynchronous. Asynchronous commands should return a Promise to indicate when they finish. Operations are collected and applied atomically after each command completes successfully.

Processes

A Process is a construct used to sequentially execute commands against a store in order to makes changes to the application state. Processes are created using the createProcess factory function that accepts a list of commands and optionally a list of middleware.

Creating a process

First, create a couple commands responsible for obtaining a user token and use that token to load a User. Then create a process that uses those commands. Every process must be identified by a unique process ID. This ID is used internally in the store.

  1. import { createCommandFactory, createProcess } from "@dojo/framework/stores/process";
  2. import { State } from './interfaces';
  3. import { add, replace } from "@dojo/framework/stores/state/operations";
  4. const createCommand = createCommandFactory<State>();
  5. const fetchUser = createCommand(async ({ at, get, payload: { username, password } }) => {
  6. const token = await fetchToken(username, password);
  7. return [
  8. add(path('auth', 'token'), token);
  9. ];
  10. }
  11. const loadUserData = createCommand(async ({ path }) => {
  12. const token = get(path('auth', 'token'));
  13. const user = await fetchCurrentUser(token);
  14. return [
  15. replace(path('users', 'current'), user)
  16. ];
  17. });
  18. export const login = createProcess('login', [ fetchUser, loadUserData ]);

payload type

The process executor’s payload is inferred from the payload type of the commands. If the payloads differ then it is necessary to explictly define the payload type.

  1. const createCommand = createCommandFactory<State>();
  2. const commandOne = createCommand<{ one: string }>(({ payload }) => {
  3. return [];
  4. });
  5. const commandTwo = createCommand<{ two: string }>(({ payload }) => {
  6. return [];
  7. });
  8. const process = createProcess<State, { one: string; two: string }>('example', [commandOne, commandTwo]);
  9. process(store)({ one: 'one', two: 'two' });

Connecting widgets and stores

There are two state containers available for widgets: StoreContainer and StoreProvider. These containers connect the application store with a widget. When using functional widgets, a typed store middleware can also be created.

Note that the documentation in this section is intended to show how widgets and state (provided by a store) are connected. For more information on widget state management in general, see the Creating Widgets reference guide.

Store middleware

When using function-based widgets, the createStoreMiddleware helper can be used to create a typed store middleware that provides a widget access to the store.

middleware/store.ts

  1. import createStoreMiddleware from '@dojo/framework/core/middleware/store';
  2. import { State } from '../interfaces';
  3. export default createStoreMiddleware<State>();

widgets/User.tsx

  1. import { create } from '@dojo/framework/core/vdom';
  2. import store from '../middleware/store';
  3. import { State } from '../../interfaces';
  4. const factory = create({ store }).properties();
  5. export const User = factory(function User({ middleware: { store } }) {
  6. const { get, path } = store;
  7. const name = get(path('users', 'current', 'name'));
  8. return <h1>{`Hello, ${name}`}</h1>;
  9. });

This middleware contains an executor method that can be used to run processes on the store.

  1. import { create } from '@dojo/framework/core/vdom';
  2. import store from '../middleware/store';
  3. import logout from '../processes/logout';
  4. import { State } from '../../interfaces';
  5. const factory = create({ store }).properties();
  6. export const User = factory(function User({ middleware: { store } }) {
  7. const { get, path } = store;
  8. const name = get(path('users', 'current', 'name'));
  9. const onLogOut = () => {
  10. store.executor(logout)({});
  11. };
  12. return (
  13. <h1>
  14. {`Hello, ${name}`}
  15. <button onclick={onLogOut}>Log Out</button>
  16. </h1>
  17. );
  18. });

StoreProvider

A StoreProvider is a Dojo widget that has its own renderer and connects to the store. It is always encapsulated in another widget because it does not define its own properties.

widget/User.ts

  1. import { create } from '@dojo/framework/core/vdom';
  2. import { State } from '../../interfaces';
  3. const factory = create().properties();
  4. export const User = factory(function User() {
  5. return (
  6. <StoreProvider
  7. stateKey="state"
  8. paths={(path) => [path('users', 'current')]}
  9. renderer={(store) => {
  10. const { get, path } = store;
  11. const name = get(path('users', 'current', 'name'));
  12. return <h1>{`Hello, ${name}`}</h1>;
  13. }}
  14. />
  15. );
  16. });

The StoreProvider occurs as part of User‘s render and provides its own renderer like any other Dojo widget.

Container

A Container is a widget that fully encapsulates another widget. It connects the store to the widget with a getProperties function.

widget/User.tsx

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. interface UserProperties {
  3. name?: string;
  4. }
  5. const factory = create().properties<UserProperties>();
  6. export const User = factory(function User({ properties }) {
  7. const { name = 'Stranger' } = properties();
  8. return <h1>{`Hello, ${name}`}</h1>;
  9. });

widget/User.container.ts

  1. import { createStoreContainer } from '@dojo/framework/stores/StoreContainer';
  2. import { State } from '../interfaces';
  3. import User from './User';
  4. const StoreContainer = createStoreContainer<State>();
  5. const UserContainer = StoreContainer(User, 'state', {
  6. getProperties({ get, path }) {
  7. const name = get(path('user', 'current', 'name'));
  8. return { name };
  9. }
  10. });

In this example UserContainer wraps User to display the current user’s name. createStoreContainer is a wrapper that gets used to ensure the proper typing of getProperties. getProperties is responsible for accessing data from the store and creating properties for the widget.

A StoreContainer‘s properties are a 1:1 mapping to the widget it wraps. The widget’s properties become the properties of the StoreContainer, but they are all optional.

Executing a process

A process simply defines an execution flow for a set of data. To execute a process, the process needs access to the store to create an executor. Both the StoreContainer and StoreProvider widgets provide access to the store.

  1. import { logout } from './processes/logout';
  2. import StoreProvider from '@dojo/framework/stores/StoreProvider';
  3. import { State } from '../../interfaces';
  4. import User from './User';
  5. import { create, tsx } from '@dojo/framework/core/vdom';
  6. const factory = create().properties();
  7. export const UserProvider = factory(function UserProvider() {
  8. return (
  9. <StoreProvider
  10. stateKey="state"
  11. paths={(path) => [path('users', 'current')]}
  12. renderer={(store) => {
  13. const { get, path } = store;
  14. const name = get(path('users', 'current', 'name'));
  15. const onLogOut = () => {
  16. logout(store)({});
  17. };
  18. return <User name={name} onLogOut={onLogOut} />;
  19. }}
  20. />
  21. );
  22. });