Redux Stores
Redux stores are used to maintain global state
The term "store" in this article refers to a JavaScript object we can use to keep track of state. Not to be confused with Magento stores.
ScandiPWA uses Redux to keep track of global state. If used correctly, Redux is predictable and easy to debug.
If you need to keep a state that will be the same throughout the application, and possibly shared between multiple components, create a Redux store. Examples:
  • Breadcrumbs are stored in a Redux store, because multiple pages need to be able to set them
  • The Cart is stored in a Redux store, because both the cart overlay and the cart page need to use it, though they don't have a direct parent-child relationship. Also, it is guaranteed that you will need information about only 1 cart in the application.
Avoid using a global Redux store if it is component-specific, and you need to be able to store a different value in each component. Use the component's state instead.
Following Redux practices, the ScandiPWA theme contains 1 Redux store. However, since the application needs to maintain different kinds of global state, the top-level Redux store actually tracks an object containing multiple "sub-stores". Each of these sub-stores, has a dedicated subdirectory in store where it is defined.
The use of Redux stores is not ScandiPWA-specific, so it is best to learn about it from the oficial redux documentation. However, we will go though an example of how it is used in ScandiPWA to help you understand how it interacts with the application.

Example: Breadcrumbs

At the top of many pages in the ScandiPWA theme, you will see breadcrumbs. These are path-like indicators that help the user understand where in the app they currently are, and improve navigation:
Since we would never need to keep track of multiple different breacrumb paths at once, they are implemented in a global redux store. Once a component receives enough data to know what the breadcrumbs should be (such as a list of parent categories as above), it dispatches an update to the breadcrumbs. This state can now be read by the component responsible for rendering breadcrumbs.

1. The .reducer File: Defining the State

The first step in creating a redux store is defining what it's initial state should be. We need to keep track of two things - the breadcrumbs themselves and a boolean indicating wether they should be visible on the current page.
1
/** @namespace Store/Breadcrumbs/Reducer/getInitialState */
2
export const getInitialState = () => ({
3
breadcrumbs: [],
4
areBreadcrumbsVisible: true
5
});
Copied!
Now, we need to describe how the state should update in response to certain actions. It might seem unintuitive at first, but Redux state cannot be updated directly. Instead, you are allowed to define reducers - functions that describe how the state should transition when an action is dispatched.
We want to handle two types of actions - one that updates the breadcrumbs, and one that updates their visibility:
1
// action types are actually defined in the .action file
2
export const UPDATE_BREADCRUMBS = 'UPDATE_BREADCRUMBS';
3
export const TOGGLE_BREADCRUMBS = 'TOGGLE_BREADCRUMBS';
Copied!
All actions are simple JavaScript objects that carry information which the reducer can interpret to update the state. The UPDATE_BREADCRUMBS action would look like this:
1
{
2
// all actions have a `type` field that indicates
3
// what kind of action it is. it must be unique
4
// among action types
5
type: UPDATE_BREADCRUMBS,
6
// the UPDATE_BREADCRUMBS type action also has a
7
// breadcrumbs field that carries information
8
// about what the new breadcrumbs should be
9
breadcrumbs: [...] // some array
10
}
Copied!
The TOGGLE_BREADCRUMBS would be similar, but carry a different type of data, a boolean:
1
{
2
type: TOGGLE_BREADCRUMBS,
3
// the UPDATE_BREADCRUMBS type action also has a
4
// breadcrumbs field that carries information
5
// about what the new breadcrumbs should be
6
areBreadcrumbsVisible: true // or false
7
}
Copied!
Note that, by themselves, actions do not do anything - they are just objects with some fields. However, when an action is dispatched ("sent" to Redux, we'll get to that later), Redux passes it on to all reducers (functions we define). Each reducer can look at the action and update its state by returning a new value.
1
/** @namespace Store/Breadcrumbs/Reducer */
2
export const BreadcrumbsReducer = (
3
state = getInitialState(), // previous state, or the initial state if none
4
action // we get the action that was dispatched
5
) => {
6
// we are only interested in certain types of actions
7
switch (action.type) {
8
9
// if this is an UPDATE_BREADCRUMBS action
10
case UPDATE_BREADCRUMBS:
11
// we know that it will have some data in action.breadcrumbs
12
const { breadcrumbs } = action;
13
​
14
// we update the state
15
return {
16
...state, // to keep the same value
17
breadcrumbs // except with a new breadcrumbs value
18
};
19
​
20
// similarly we want to update the state for TOGGLE_BREADCRUMBS actions
21
case TOGGLE_BREADCRUMBS:
22
const { areBreadcrumbsVisible } = action;
23
​
24
return {
25
...state,
26
areBreadcrumbsVisible
27
};
28
​
29
default:
30
// it is possible the action was not related to breadcrumbs.
31
// then we can just return the original state unchanged.
32
return state;
33
}
34
};
Copied!
Now that the reducer is defined, we need to include it in our single global Redux state.
src/app/store/index.js (simplified & annotated)
1
// copyright
2
​
3
import {
4
combineReducers,
5
createStore
6
} from 'redux';
7
​
8
import BreadcrumbsReducer from 'Store/Breadcrumbs/Breadcrumbs.reducer';
9
// [...] import the other reducers
10
​
11
/** @namespace Store/Index/getReducers */
12
export const getStaticReducers = () => ({
13
BreadcrumbsReducer,
14
// [...] include the other reducers
15
});
16
​
17
// a bunch of Redux API calls essentially creating a store from the above
Copied!

2. The .action File: Defining Possible Actions

The reducer we created can respond to certain actions described above, but creating those action object manually would get repetitive and error-prone. Hence, we create functions that can create these action objects for us:
store/Breadcrumbs/Breadcrumbs.action.js (simplified)
1
export const UPDATE_BREADCRUMBS = 'UPDATE_BREADCRUMBS';
2
export const TOGGLE_BREADCRUMBS = 'TOGGLE_BREADCRUMBS';
3
​
4
export const updateBreadcrumbs = (breadcrumbs) => ({
5
type: UPDATE_BREADCRUMBS,
6
breadcrumbs
7
});
8
​
9
export const toggleBreadcrumbs = (areBreadcrumbsVisible) => ({
10
type: TOGGLE_BREADCRUMBS,
11
areBreadcrumbsVisible
12
});
13
​
Copied!
Redux strongly discourages creating side effects in the reducer, or action creators. Avoid making requests, mutating non-Redux state, or other changes in these functions. This will make them less predictable and harder to debug.

3. The .dispatcher File: Dispatching Helpers

It can be convenient to have a file that defines helpers for dispatching actions. That's what the .dispatcher file is for:
store/Breadcrumbs/Breadcrumbs.dispatcher.js (simplified, annotated)
1
import { toggleBreadcrumbs, updateBreadcrumbs }
2
from 'Store/Breadcrumbs/Breadcrumbs.action';
3
​
4
/** @namespace Store/Breadcrumbs/Dispatcher */
5
export class BreadcrumbsDispatcher {
6
// utility method for updating breadcrumbs
7
// given a category,
8
// and a dispatch function (from Redux)
9
updateWithCategory(category, dispatch) {
10
const breadcrumbs = this._getCategoryBreadcrumbs(category);
11
dispatch(toggleBreadcrumbs(true));
12
dispatch(updateBreadcrumbs(breadcrumbs));
13
}
14
15
_getCategoryBreadcrumbs(category) {...}
16
​
17
updateWithProduct(product, dispatch) {...}
18
​
19
updateWithCmsPage(cmsPage, dispatch) {...}
20
}
21
​
22
export default new BreadcrumbsDispatcher();
Copied!
Unlike the reducer or action creators, you are free to have side effects in the dispatcher. For example, in store/Cart/Cart.dispatcher.js, addProductToCart makes a GraphQl mutation request before updating the store by dispatching a cart data update.

4. Usage in Components

Any component's container can read and dispatch to the Redux state by using the connect higher-order component.

Reading the state: Example

1
import { connect } from 'react-redux';
2
​
3
import Breadcrumbs from './Breadcrumbs.component';
4
​
5
// given the global state, need to return an object
6
// containing the values of the state that we need
7
// these will be passed as props to Breadcrumbs
8
/** @namespace Component/Breadcrumbs/Container/mapStateToProps */
9
export const mapStateToProps = (state) => ({
10
breadcrumbs: state.BreadcrumbsReducer.breadcrumbs,
11
areBreadcrumbsVisible: state.BreadcrumbsReducer.areBreadcrumbsVisible
12
});
13
​
14
// we specify mapDispatchToProps even though we don't need it
15
// so that ScandiPWA plugins can use it if necessary
16
/** @namespace Component/Breadcrumbs/Container/mapDispatchToProps */
17
export const mapDispatchToProps = () => ({});
18
​
19
// Breadcrumbs will get breadcrumbs and areBreadcrumbsVisible as props
20
export default connect(mapStateToProps, mapDispatchToProps)(Breadcrumbs);
Copied!

Dispatching to the state: Example

route/CategoryPage/CategoryPage.container.js (simplified, annotated)
1
// we use a lazy import for better performance
2
export const BreadcrumbsDispatcher = import(
3
/* webpackMode: "lazy", webpackChunkName: "dispatchers" */
4
'Store/Breadcrumbs/Breadcrumbs.dispatcher'
5
);
6
​
7
/** @namespace Route/CategoryPage/Container/mapStateToProps */
8
export const mapStateToProps = (state) => {...};
9
​
10
/** @namespace Route/CategoryPage/Container/mapDispatchToProps */
11
export const mapDispatchToProps = (dispatch) => ({
12
updateBreadcrumbs: (breadcrumbs) => ((Object.keys(breadcrumbs).length)
13
? BreadcrumbsDispatcher.then( // promise to load BreadcrumbsDispatcher
14
({ default: dispatcher }) =>
15
dispatcher.updateWithCategory(breadcrumbs, dispatch)
16
)
17
: BreadcrumbsDispatcher.then(
18
({ default: dispatcher }) =>
19
dispatcher.update([], dispatch)
20
)
21
),
22
// [...]
23
});
24
​
25
/** @namespace Route/CategoryPage/Container */
26
export class CategoryPageContainer extends PureComponent {
27
// updateBreadcrumbs will be passed as props when
28
// react-redux wraps the component
29
static propTypes = {
30
updateBreadcrumbs: PropTypes.func.isRequired,
31
// [...]
32
};
33
​
34
componentDidMount() {
35
this.updateBreadcrumbs();
36
}
37
​
38
componentDidUpdate(prevProps) {
39
this.updateBreadcrumbs();
40
}
41
​
42
updateBreadcrumbs(isUnmatchedCategory = false) {
43
// we can simply get the function from props and call it
44
const { updateBreadcrumbs, category } = this.props;
45
const breadcrumbs = isUnmatchedCategory ? {} : category;
46
updateBreadcrumbs(breadcrumbs);
47
}
48
49
render() {...}
50
}
51
​
52
export default connect(mapStateToProps, mapDispatchToProps)
53
(CategoryPageContainer);
Copied!
​
Last modified 10mo ago