⊗jsrxPmRDAS 27 of 57 menu

Adding another slice to Redux

In previous lessons, we worked hard on the products slice for products. In a real Redux application, the state may have many slices for different purposes. So in this lesson, we will add another slice to the state for sellers, who will actually add products in our application.

Let's open our product app and the first thing we'll do is create another folder parts in the parts folder, here we'll place all the code and components related to sellers.

Now, just like with products, let's create a slice for sellers. First, in the sellers folder, create a file sellersSlice.js and import createSlice into it:

import { createSlice } from '@reduxjs/toolkit'

We continue with the standard steps. As an initial value for the slice, we will create four sellers. For simplicity, they will have two fields - id and name:

const initialState = [ { id: '0', name: 'Super Power' }, { id: '1', name: 'Miracle Life' }, { id: '2', name: 'Dolls&Toys' }, { id: '3', name: 'Granny' }, ]

Below, using createSlice, we will create a slice sellers, and pass it the initial value. Since we will neither add sellers nor update their data in the future, let the field with reducers remain empty for now:

const sellersSlice = createSlice({ name: 'sellers', initialState, reducers: {}, })

At the end of the file, let's not forget about exporting the resulting reducer:

export default sellersSlice.reducer

Now we need to open the store.js file in the app folder and import the resulting reducer:

import sellersReducer from "../parts/sellers/sellersSlice"

And then assign it in configureStore as a reducer for sellers:

export default configureStore({ reducer: { products: productsReducer, sellers: sellersReducer, }, })

Open your app with students. Create another folder teachers, here you will have files with code related to teachers. Create a file teachersSlice.js in it. Using the lesson materials, create a slice teachers in it using createSlice.

Let each object with teacher data have three properties: id, name (which will contain the last name and initials, for example 'Petrov A.V.') and a subject (any you can think of - physics, mathematics, biology, etc.). Make 3 such objects with teachers as the initial value for the slice.

Import the resulting teachersReducer reducer into store.js and assign it as a reducer for teachers as shown in the tutorial.

enru