AlexZeDim
AlexZeDim

Reputation: 4352

ReactJS many tables from one data array/json/request from DB

I'm new with React and I like to built the same tables on my frontage with such data

Example data from MongoDB:

{name:"flower1", price: 5, quantity: 34, color:"red"}
{name:"flower2", price: 4, quantity: 57, color:"blue"}
{name:"flower3", price: 6, quantity: 56, color:"white"}
{name:"flower4", price: 6, quantity: 56, color:"red"}
{name:"flower5", price: 8, quantity: 56, color:"blue"}

but with only one type in every table

Table structure:

{table_name_by_color_from_DB}
Name | Price | Quantity

For example I have 3 different colors, so it should be three tables. I could easily create tables in React, but each time when I want to create table, I should request data from Mongo. If I have 10 colors I should create 10 tables, and I'm afraid that it will be too much requests. So what's the best practice to do so? Can I just request Mongo once and then separate data from response for each table by color with .map? Could someone provide advice or a code-snippet for that?

Upvotes: 0

Views: 109

Answers (1)

ugrpla
ugrpla

Reputation: 403

you could use the groupBy helper from lodash

groupBy(data, 'color') 

will restructure your data into

{
    red: [
        {name:"flower1", price: 5, quantity: 34, color:"red"},
        {name:"flower4", price: 6, quantity: 56, color:"red"}
    ],
    blue: [
        {name:"flower2", price: 4, quantity: 57, color:"blue"},
        {name:"flower5", price: 8, quantity: 56, color:"blue"}
    ],
    white: [
        {name:"flower3", price: 6, quantity: 56, color:"white"}
    ]
}

and you can map that into your Table Component

{
   Object.keys(data).map(color => (
       <TableComponent data={data[color]} />
   ))
}

Upvotes: 1

Related Questions