Creating a Product Data Object in Redux
We have a function for creating an object with a seller, let's move on to the product. Creating this object will be a little more complicated, since it contains more data fields. Let's get started.
Let's open our product app, and in it the file server.js
. Below, after the function getRandInt
, we'll write our function createProductData
:
const createProductData = () => {}
Now let's write the properties we need. We'll generate the values for name
, price
and amount
using getRandInt
, which we wrote in the last lesson:
const createProductData = () => {
return {
name: `Product${getRandInt(0, 100)}`,
price: getRandInt(100, 2000),
amount: getRandInt(1, 50),
}
}
And in order to generate the description, we will use another useful thing. This is the faker library, which allows you to generate fake names, addresses, emails, street names, texts, etc. in different languages. Let's enter the following line in the terminal and install this library for our application:
npm install @faker-js/faker --save-dev
And then we import it into our file:
import { faker } from '@faker-js/faker'
Let's use it to generate sentences containing the well-known "fish" text 'Lorem ipsum'
. Let the description contain from 3
to 5
such sentences:
const createProductData = () => {
return {
name: `Product${getRandInt(0, 100)}`,
desc: faker.lorem.sentences({ min: 3, max: 5 }),
price: getRandInt(100, 2000),
amount: getRandInt(1, 50),
}
}
Now let's add a field with reactions to our object, and we'll pass it a value generated on the spot by the create
command, an object (for now, the reactions in it will be 0
):
const createProductData = () => {
return {
name: `Product${getRandInt(0, 100)}`,
desc: faker.lorem.sentences({ min: 3, max: 5 }),
price: getRandInt(100, 2000),
amount: getRandInt(1, 50),
reactions: db.reaction.create(),
}
}
And the last property we add is the already generated seller object, which we must pass as a parameter to the createProductData
function. This is what the full code for the product object creation function looks like:
const createProductData = (seller) => {
return {
name: `Product${getRandInt(0, 100)}`,
desc: faker.lorem.sentences({ min: 3, max: 5 }),
price: getRandInt(100, 2000),
amount: getRandInt(1, 50),
reactions: db.reaction.create(),
seller,
}
}
Open your application with students. After reviewing the material of this lesson, write a function to create an object with student data.