Adding basket state and actions to the store

We'll add state management for our basket in this section. We'll create a new section in our store for this.

  1. First, let's create a new file for the types called BasketTypes.ts with the following content:
import { IProduct } from "./ProductsData";

export enum BasketActionTypes {
ADD = "BASKET/ADD"
}

export interface IBasketState {
readonly products: IProduct[];
}

export interface IBasketAdd {
type: BasketActionTypes.ADD;
product: IProduct;
}

export type BasketActions = IBasketAdd;
  • There is only one piece of state in our basket and that's an array of products in the basket.
  • There is only one action as well. This is to add a product to the basket.
  1. Let's create a file called BasketActions.ts with the following content:
import { BasketActionTypes, IBasketAdd } from "./BasketTypes";
import { IProduct } from "./ProductsData";

export const addToBasket = (product: IProduct): IBasketAdd => ({
product,
type: BasketActionTypes.ADD
});

This is the action creator for adding to the basket. The function takes in a product and returns it in the action with the appropriate action type.

  1. On to the reducer now. Let's create a file called BasketReducer.ts with the following import statements:
import { Reducer } from "redux";
import { BasketActions, BasketActionTypes, IBasketState } from "./BasketTypes";
  1. Let's create an object for the initial basket state:
const initialBasketState: IBasketState = {
products: []
};
  1. Let's create the reducer now:
export const basketReducer: Reducer<IBasketState, BasketActions> = (state = initialBasketState, action) => {
switch (action.type) {
case BasketActionTypes.ADD: {
return {
...state,
products: state.products.concat(action.product)
};
}
}
return state || initialBasketState;
};

This follows the same pattern as productsReducer.

One interesting point to note is how we elegantly add the product to the products array without mutating the original array. We use the JavaScript concat function, which creates a new array by merging the original with the parameter passed in. This is a great function to use in reducers where state changes involve adding items to arrays.

  1. Let's open up Store.ts now and import the new reducer and state for the basket:
import { basketReducer } from "./BasketReducer";
import { IBasketState } from "./BasketTypes";
  1. Let's add the basket state to the store:
export interface IApplicationState {
basket: IBasketState;
  products: IProductsState;
}
  1. We have two reducers now. So, let's add the basket reducer to the combineReducers function call:
export const rootReducer = combineReducers<IApplicationState>({
basket: basketReducer,
products: productsReducer
});

Now that we've adjusted our store, we can connect our ProductPage component to it.

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

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