⊗jsrxPmATDT 54 of 57 menu

Sending Data with Thunk in Redux

In the last lesson we figured out how to handle a POST request on our fake server. Now let's write a thunk function that will send a request to the server.

Let's open our product app, and in it the file productsSlice.js. Now after the thunk fetchProducts we will use createAsyncThunk to create the thunk addProduct:

export const addProduct = createAsyncThunk()

The first parameter we will pass to createAsyncThunk 'products/addProduct', and the second one is an asynchronous callback that will receive an object with the data of the new product:

export const addProduct = createAsyncThunk( 'products/addProduct', async (newProduct) => {} )

In the code of this callback, we will call the client, passing it the path and the product object as parameters, and then return the response data:

export const addProduct = createAsyncThunk( 'products/addProduct', async (newProduct) => { const response = await client.post('/fakeServer/products', newProduct) return response.data } )

Now, below in the code, let's look at the reducers field for productsSlice. Previously, we added a new product using the productAdded reducer, in which we had the reducer and prepare methods. Now, we generate the necessary data on the server and work with thunk, so we'll remove the productAdded reducer from the code here completely. And then we'll add another additional reducer to the extraReducers method (to the end of its code), which, in case of a successful request, will add a new product to the products slice directly from the payload action (remember that such code is only possible thanks to the unique createSlice):

.addCase(addProduct.fulfilled, (state, action) => { state.products.push(action.payload) })

Oh, by the way, don't forget to remove nanoid from the import lines, and productAdded from the action export at the end of the file.

Open your students app. Open the studentsSlice.js file in it. Using createAsyncThunk, create another thunk addStudent that will send a POST request to the server to add a new student, as shown in the lesson.

Next, below make changes for studentsSlice: remove the studentAdded reducer completely in the reducers property. And in the extraReducers field, add an additional reducer that will add a new student to the students slice from the payload action in case of a successful request, as shown in the tutorial.

enru