0

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?

2
  • 1
    Don't put a burden on reactjs. Instead get table data in a structured format from nodejs. Your API should provide a separate array for each color and show table for each array. What you think Commented Jul 2, 2018 at 9:57
  • yeah, you right, at first I thought about it, but it's a bit more complicated than that. It's about 10+ "colors" and I should request DB from another collection to make receive result data for creating table. So it's will be already [color x 2] request to DB, but the key problem here, that I write a lot of data (almost realtime) and it's a bit loaded. But, as for now, I get X requests via API (by colors) Commented Jul 2, 2018 at 10:05

1 Answer 1

1

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]} />
   ))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.