Adding a Slice to Redux
We have prepared the basic tools for creating our Redux application, now we can move directly to the implementation of its components.
In this lesson we'll start with the concept of slices. A Redux application has one global state, which is stored in the store. This state is split into slices. In fact, a slice is a piece of the store that contains the original state, reducer logic, and actions for a specific part of the application.
Our application will feature products, so the first slice we make will contain information about products. Also, when creating a slice, you need to add a reducer that knows how to process this information.
Let's go into the src
folder and create a parts
folder, and then a products
folder in it - we'll put all the files with code related to products here. In the products
folder, we'll create a productsSlice.js
file, and then import the createSlice
function from RTK into it, which we'll use to create slices:
import { createSlice } from '@reduxjs/toolkit'
Now let's create a slice for products and call it 'products'
. For the reducers
property, we'll leave the curly braces empty for now:
const productsSlice = createSlice({
name: 'products',
initialState,
reducers: {}
})
We also need to define initialState
- the initial state of the state slice, which will be loaded when the application is first launched. Let's write it right after import and before creating the slice. Let it be an array of a pair of objects containing product data. Let's specify for each product id
, name, description, price and quantity:
const initialState = [
{
id: '1',
title: 'Product1',
desc: 'This is an amazing product',
price: '300',
amount: '30',
},
{
id: '2',
title: 'Product2',
desc: 'This is a nice product',
price: '700',
amount: '12',
},
]
At the end of the file code, we take the reducer generated by the createSlice
function and export it. We will need it in other files of the application:
export default productsSlice.reducer
Open your student app. Create a file studentsSlice.js
in it, as described in the lesson. In it, create a slice students
using createSlice
. As an initial value of the slice, let it be an array of a pair of objects containing the students' data.
For each student, create the following fields: id
, first name, last name, age, and specialty.
At the end of the studentsSlice.js
file, export the resulting reducer as described in the tutorial.