Creating the store

The final task in Store.ts is to create a function that creates the store. Let's do this by carrying out the following steps:

  1. First, let's import the Store type and createStore and applyMiddleware functions from Redux, along with the thunk object from Redux Thunk:
import {
Action,
ActionCreator,
Dispatch,
Reducer,
combineReducers,
Store,
createStore,
applyMiddleware
} from 'redux';
import thunk, { ThunkAction } from 'redux-thunk';
  1. Let's create a function to create the store:
export function configureStore(): Store<AppState> {
const store = createStore(
rootReducer,
undefined,
applyMiddleware(thunk)
);
return store;
}

This function uses the createStore function from Redux by passing in the combined reducers, undefined as the initial state, and the Thunk middleware using the applyMiddleware function. Remember that Thunk is used to enable asynchronous actions because, by default, Redux actions can't be asynchronous.

We use the generic Store type as the return type for the function passing in the interface for our app state, which is AppState.

That's all we need to do to create the store.

We have created all the bits and pieces in our store in a single file called Store.ts. For larger stores, it may help maintainability to structure the store across different files. Structuring the store by feature where you have all the actions and the reducer for each feature in a file works well because we generally read and write our code by feature. 

In the next section, we will connect our store to the components we implemented in the previous chapters.

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

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