Creating Basket Slice
In this lesson, we're going to create a basket slice
Creating basket slice#
Now that we've introduced redux-toolkit and also implemented it with a test loginSlice, I think we're ready to refactor our application using redux-toolkit. We can now create our basket slice inside slice
folder. We will start with the BasketState; first, let's create an interface BasketState. Here, we will have basket which will be of type Basket or null. Next step is to create the initialState; the type will be BasketState and value will be null. We are now ready to create the basketSlice.
Export const basketSlice (which will be equal to the createSlice method, and as you know, it expects name which will be basket), the initial state and the reducers. Our first action creator is the setBasket. It will accept state and action, and will return state.basket is equal to action.payload. Next action is the removeItem; let's pass action and payload. As you know, our removeItem action will accept courseId as a parameter, so we can destructure it from action.payload. Now, we will calculate the itemIndex using findIndex method, and we will use the method on state.basket.Items and check if i.courseId is equal to the courseId. If it is undefined or -1, we can return. Otherwise, we can splice the basket items using itemIndex and 1.
Finally, I can export setBasket and removeItem from basketSlice.actions. We are not returning the basket state explicitly because we don't have to; we can simply use useSelector method and get a slice of state that we need. We can provide the basketSlice reducer to the configureStore; let's go there and pass basket with value basketSlice.reducer. Our basketSlice is now ready. We can refactor our application to use Redux instead of using ContextAPI, in the next lesson.
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React