In this guide, you will learn to add a new Redux store to your app. To learn more about Redux stores in Scandi, read the docs.
Creating a New Store
First, we need to create a new Redux store. Using the scandipwa CLI utility, you can easily create a new store with a single command. In our toy example, we will call our store ImportantNumber:
scandipwacreatestoreImportantNumber
You should see that new files have been created, as indicated by a success message:
NOTE!
The following files have been created:
src/store/ImportantNumber/ImportantNumber.action.js
src/store/ImportantNumber/ImportantNumber.reducer.js
Feel free to implement any logic you need in the Redux store.
Redux in Scandi
At this point, you will notice that while we have defined the store in the codebase, it is not registered in the app yet. This is because it hasn't been registered yet.
In Scandi, stores are registered in the store/index.js file:
As you can see, most reducers are registered in the getStaticReducers function. To add a new reducer, we must override this function, and add our own reducer. We must also override injectStaticReducers to use our new function.
Confused by the object notation syntax? In JavaScript, spelling out the key name is optional if it's the same as the value variable. So writing...
So how can we override the index.js file? Unfortunately, at the moment, the CLI cannot automate this for us, so you need to create a new file for overriding manually:
src/store/index.js
// import the original getStaticReducers function// and rename it to baseGetStaticReducersimport { getStaticReducers as baseGetStaticReducers } from'SourceStore/index';// import our own reducerimport ImportantNumberReducer from'Store/ImportantNumber/ImportantNumber.reducer';// define getStaticReducers.// this is a function that returns an object of all the reducers in the app.// just like in the base theme.../** @namespace TutorialCsaApp/Store/Index/getStaticReducers */exportconstgetStaticReducers= () => ({...baseGetStaticReducers(),// ...except we also add our own reducer to the mix ImportantNumberReducer});// nothing new here, just copying the function from the base theme// (this is necessary so that it uses our own `getStaticReducers` functionexportdefaultfunctioninjectStaticReducers(store) {Object.entries(getStaticReducers()).forEach( ([name, reducer]) =>store.injectReducer(name, reducer) );return store;}
Aaand that's it! If you check the Redux developer tools, you will see that your reducer is now included in the state.