Creating Category Slice
In this lesson, we're going to create a category slice
Creating category slice#
We have centralized our course's data by creating courseSlice. We can see that we're making categories request again and again whenever we go to the homepage. Let's centralize that too. This also gives us an opportunity to practice redux toolkit skills. Let's go to the redux folder and create categorySlice.
We can start by creating a const called categoriesAdapter which will be equal to createEntityAdapter of type category. We can now create a function which will fetch the categories. Let's export it and call it getCategoriesAsync which will be equal to the createAsyncThunk. We will receive an array of Category or undefined. We are not passing any parameter here so we can write void. Let's call it category/getCategoriesAsync. Let's write async and write our try catch block, then let's log the error inside the catch block and return await agent.Categories.list.
Let's create our categorySlice now. We will use the createSlice and name it category. For the initial state, we can use categoriesAdapter.getInitialState and we can use categoriesLoaded and keep it false and status will be idle. We can keep our reducers empty, and we can write extraReducers with builder. Inside, we can write our addCases. The first one will be for getCategoriesAsync.pending. Here, we just need the state and we can set the status to be pending. The next addCase will be for the fulfilled; we can copy it and use action with the state. Inside, we can use categoriesAdapter.setMany with state and action.payload. Let's change the status to be idle and state.categoriesLoaded to be true. Finally, for the rejected case, we can keep it the same as the pending case.
In the bottom, I will write the categoriesSelector which will be equal to the categoriesAdapter.getSelectors, and state will be of type RootState. We want to select state.category from the state. We don't see the category option because we haven't included it inside our configureStore file, so let's do that right now. Now, if we go back, we see category being shown.