State Persistence
Prior to composable storefront version 2.0, the only way to achieve state persistence was by using a simple, declarative mechanism called storageSync, which allowed you to provide properties keys to persist in the store. When you started your application, these persisted keys were used to set the initial state in the store. With composable storefront version 2.0 or newer, you can persist the state of your storefront application by using the StatePersistenceService, and specifically, its syncWithStorage method. It is not as simple as storageSync, but it provides a lot more control using context and dedicated onRead callback.
You can pass the following options to the syncWithStorage function: key, state$, context$, storageType, and onRead.
These options work as follows:
-
key is used to distinguish one feature from another in storage. For example, to store the active cart id, you can use the cart key, and for the user session data, you can use the session key.
-
state$ is an observable that emits a value every time you want to save the new value to the persistent storage. For example, to persist the active cart id every time the active cart id changes, this observable emits a new value.
-
context$ is an observable that describes a valid context for a particular state. For example, the active cart id is valid only for one base site. On different base sites, you want to use different carts. In this case, with context$, you would use an observable that emits the base site every time it changes.
-
storageType specifies the storage type that is used. By default, the storage type is local storage, but you can change this to session storage, for example.
-
onRead is a callback that is invoked every time the context changes. To use the cart as an example, every time you change the base site, this callback is called with a value read from storage for that particular context. It will dispatch a value of undefined if there is nothing saved in storage.
Implementing Complete State Persistence for a Feature
The following steps describe how to implement state persistence for a feature, using the cart as an example:
Procedure
State Synchronization in Action
The following is an example description of state synchronization with an electronics and an apparel storefront. In this example, the state persistence service is set up as follows:
-
key: "cart"
-
state$ : points to the active cart id selector
-
context$: this.siteContextParamsService.getValues([BASE_SITE_CONTEXT_ID]) // The cart is valid only on the same base site
-
onRead: function dispatches ClearCart action, and then SetActiveCartId when the id is read from storage
State Synchronization Example
The following describes an example flow of the state synchronization: