Creating a store

In this section, we'll create a store that is going to hold our state and manage the actions and reducer:

  1. Let's start off by creating a new file called Store.tsx with the following import statement to get the bits and pieces we need from Redux:
import { applyMiddleware, combineReducers, createStore, Store } from "redux";
  • createStore is a function we'll eventually use to create our store
  • We need the applyMiddleware function because we need to use the Redux Thunk middleware to manage our asynchronous actions
  • The combineReducers function is a function we can use to merge our reducers together
  • Store is a TypeScript type we can use for the store
  1. Let's import redux-thunk:
import thunk from "redux-thunk";
  1. Finally, let's import our reducer and state type:
import { productsReducer } from "./ProductsReducer";
import { IProductsState } from "./ProductsTypes";
  1. A key part of the store is the state. So, let's define an interface for this:
export interface IApplicationState {
products: IProductsState;
}

At this point, the interface simply contains our products state.

  1. Let's put our reducer in the Redux combineReducer function now:
const rootReducer = combineReducers<IApplicationState>({
products: productsReducer
});
  1. With the state and root reducer defined, we can create our store. We are actually going to create a function that creates the store:
export default function configureStore(): Store<IApplicationState> {
const store = createStore(rootReducer, undefined, applyMiddleware(thunk));
return store;
}
  • The function that creates our store is called configureStore and returns the generic Store type with our specific store state passed in to it.
  • The function uses the Redux createStore function to create and return the store. We pass in our reducer as well as the Redux Thunk middleware. We pass undefined as the initial state because our reducer takes care of the initial state.

We've made a great start on our store. In the next section, we'll start to connect our React shop to our store.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.130.24