⊗jsrxPmSDGRS 43 of 57 menu

Sending data from the server via GET request in Redux

So, we have a database. The first thing we will do when launching our Redux application is to get product data from the server. To do this, we need to send a GET request from our application. Let's process it on the server side.

Let's open our product app, and in it the file server.js. In order to work with HTTP requests, we need to import several tools from msw into the file, let's do this:

import { http, HttpResponse, delay } from 'msw'

We will also immediately make adjustments for reality, that is, possible delays in the network. Let the value of our artificial delay be 2 seconds, so that we can see how the data is loaded. We will write it after const PRODS_PER_SELLER = 2:

const ARTIFICIAL_DELAY_MS = 2000

Now, at the end of the file, before exporting the worker, we'll create an array for the API request handlers:

export const handlers = []

And then in square brackets we write the first handler to intercept the GET request for products:

export const handlers = [http.get()]

The first parameter for http.get we will pass some fake address, for example '/fakeServer/products', and the second an asynchronous callback:

export const handlers = [http.get('/fakeServer/products', async () => {})]

Now let's write the code for this callback. We'll use it to retrieve all the products from the database. Here we also use the serializeProduct function that we coded in the last lesson. Let's pass it to map. Then we'll make a delay (as if the network is slow) and return objects with the product data as JSON to response:

export const handlers = [ http.get('/fakeServer/products', async () => { const products = db.product.getAll().map(serializeProduct) await delay(ARTIFICIAL_DELAY_MS) return HttpResponse.json(products) }), ]

And the final touch. We have written the first handler for our worker, let's pass the handlers array to this worker. To do this, we will correct the last line of code in the file to:

export const worker = setupWorker(...handlers)

Open your students app and open the server.js file in it. Import the specified tools from msw into the file. After studying the material of this lesson, create an empty array of handlers for intercepting requests. Write the code for the students GET request handler in it. Let your path be '/fakeServer/students'.

At the end of the file, don't forget to pass the handlers handlers array to the worker.

byenru