Creating state and action types

It's time to finally make a start on enhancing our React shop with Redux. We'll start by creating some types for the state and actions for our Redux store:

  1. Let's create a new file called ProductsTypes.ts in the src folder with the following import statement at the top:
import { IProduct } from "./ProductsData";
  1. Let's create an enumeration for the two different action types that we are going to implement:
export enum ProductsActionTypes {
GETALL = "PRODUCTS/GETALL",
LOADING = "PRODUCTS/LOADING"
}

Redux doesn't dictate the format of the action type strings. So, the format of the action type strings is our choice. We need to make sure the strings are unique though across the actions types in the store. So, we've included two bits of information in the string:

  • The area of the store the action is concerned with. In our case, this is PRODUCTS.
  • The specific operation within that area. In our case, we have GETALL for getting all the products and LOADING to indicate products are being fetched. 

We could have chosen PRODUCTS-GETALL or Get All Products. We just need to make sure the strings are unique. We have used an enumeration to give us nice IntelliSense when we consume these when implementing the action and reducer.

  1. We can now create interfaces for the two actions:
export interface IProductsGetAllAction {
type: ProductsActionTypes.GETALL,
products: IProduct[]
}

export interface IProductsLoadingAction {
type: ProductsActionTypes.LOADING
}

The IProductsGetAllAction interface is for an action that will be dispatched when the products need to be fetched. The IProductsLoadingAction interface is for an action that will cause the reducer to change the loading state.

  1. Let's combine the action types together with a union type:
export type ProductsActions =
| IProductsGetAllAction
| IProductsLoadingAction

This will be the type for the action parameter passed into the reducer.

  1. Lastly, let's create an interface for this area of the state in the store:
export interface IProductsState {
readonly products: IProduct[];
readonly productsLoading: boolean;
}

So, our state will contain an array of products, and whether products are being loaded.

Notice that the properties are prefixed with the readonly keyword. This will help us avoid changing the state directly.

Now that we have types in place for the actions and state, we can create some actions in the next section.

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

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