⊗jsrxPmATGS 51 of 57 menu

Getting Seller Data in Redux

Let's run our product app. We see that the product cards don't display sellers. Let's get them from the server and display this data. To do this, we'll have to follow the same sequence of actions.

First, let's open the server.js file. Find the handlers array and add another GET request handler to it (after the GET for products). As you can see, it's almost identical:

http.get('/fakeServer/sellers', async () => { await delay(ARTIFICIAL_DELAY_MS) return HttpResponse.json(db.seller.getAll()) }),

We have processed the request on the server. The next step is to write a thunk in the sellersSlice.js file to receive data from the server. To do this, import client and createAsyncThunk into it:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit' import { client } from '../../api/client'

Now we will be getting vendors from the server, so we will remove them from initialState, leaving just empty brackets:

const initialState = []

And then before the function sellersSlice we will create our thunk fetchSellers. We will pass the path we specified on the server to the client:

export const fetchSellers = createAsyncThunk( 'sellers/fetchSellers', async () => { const response = await client.get('/fakeServer/sellers') return response.data } )

All that's left for us to do is create an additional reducer for sellersSlice. We'll limit ourselves to handling a successful request here. All actions generated by fetchSellers will be identical to those of fetchProducts:

const sellersSlice = createSlice({ name: 'sellers', initialState, reducers: {}, extraReducers(builder) { builder.addCase(fetchSellers.fulfilled, (state, action) => { return action.payload }) }, })

Let me remind you that last time when receiving products we changed the current value of the state. Here we used a slightly different path and simply returned the new value, so in createSlice you can do that too. Thus, we achieved two goals. Firstly, we received the data, and secondly, now we have a guarantee that nothing else will appear in the list of sellers, because we completely rewrote the slice with the value action.payload.

Open your application with students. Open the server.js file in it, add another handler for the GET request of teachers to the handlers array.

Now open the file teachersSlice.js. Make initialState an empty array, as shown in the tutorial. Before the function studentsSlice write thunk fetchTeachers.

In the createSlice function, add an additional reducer, limit yourself to processing a successful request.

byenru