⊗jsrxPmSDDB 38 of 57 menu

Database for server in Redux

In the last lesson we installed msw, which will help us simulate the work of our application with the server. And to begin with, we would like to load the data already available on the server when the application is launched.

Let's open our product app, and in it the file server.js. Here we already have a couple of lines of code from the last lesson.

And the first thing we should ask ourselves is: where is the data usually stored? Yes, of course in the database, we will answer without thinking. So let's use another cool tool that will allow us to create a model of our data, and also make it as if we were working with a real SQL database.

The tool that will help us with this is the library @mswjs/data. To install it, enter the following command in the terminal:

npm install @mswjs/data --save-dev

Now we import the things we need in the server.js file:

import { factory, oneOf, manyOf, primaryKey } from '@mswjs/data'

And let's create our improvised database. For this, we use the factory function. We'll do this below after the import lines and before exporting the worker:

export const db = factory({})

What data will we store in it? We should receive products, sellers and user reactions from the server. So, in our database we should create three models that factory accepts as objects:

export const db = factory({ product: {}, seller: {}, reaction: {}, })

As in a real SQL database, each of our models must have a primary key. Traditionally, we will assign such a field to id, which we will generate using the same nanoid library:

export const db = factory({ product: { id: primaryKey(nanoid), }, seller: { id: primaryKey(nanoid), }, reaction: { id: primaryKey(nanoid), }, })

Don't forget to add nanoid to the import lines at the beginning of the file:

import { nanoid } from '@reduxjs/toolkit'

In the next lesson we will supplement our models with the necessary fields.

Open your app with students. After reviewing the material in this lesson, install @mswjs/data for your application.

Next, create a db database model using the factory function. Pass it three objects (student, teacher, vote) for your data, similar to how it is shown in the tutorial.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline