⊗jsrxPmSDSSC 35 of 57 menu

Changing State Structure in Redux

The first step we will implement to interact with our Redux application with some external server is to get the data that is stored on it when the application is launched. But before that, let's make some changes to our application.

Let's open our product app, and in it the productsSlice.js file. Pay attention to the definition of initialState. Initially, our product slice productsSlice is an array that contains objects (in our case, two of them) with product data. Firstly, since we will now load them from the server, we need to remove them from initialState. Secondly, we will send API requests to the server and it will be important for us to know their status. Considering these two things, let's rework initialState. Let's now just have an object with fields products (initially there won't be any data here, just an empty array), status and error. Now our code for initialState will be a bit shorter:

const initialState = { products: [], status: 'idle', error: null, }

For now we have set the status to 'idle' (inactivity), because initially we do not send any requests, but in general it will change and can take the values ​​'loading', 'completed', 'loading error'. Remember that you can choose the names that are convenient for you to indicate the status.

Let's go down the code. After changing initialState, we should also change the code where we work with this state in the reducer functions. Let's look at the code for productAdded:

state.push(action.payload)

Now we will put new products not just in the state for products, but in its property state.products. Therefore, we will replace the above line with:

state.products.push(action.payload)

Accordingly, we will make the same changes for the reactionClicked reducer. Instead of:

const currentProduct = state.find((product) => product.id === productId)

Now it will be:

const currentProduct = state.products.find((product) => product.id === productId)

Replace state with state.products and in the reducer code productUpdated.

Open your app with students. Open the file studentsSlice.js in it. Now let your initialState have three properties: students, status, error - remake it as shown in the lesson.

Make the appropriate changes below the code. Replace state with state.students in the code for your three reducer functions.

enru