DEV Community

Cover image for Need some help & advice from React.js devs!
yoqub98
yoqub98

Posted on

Need some help & advice from React.js devs!

I am getting JSON data and assigning values to my state variables. But since there is more data I need to loop through all arrays. There is data[] array each property of which has Name, Product etc. I want to display everything in a table. Tried to use .map() but got confused. How can I map through data[] and assign the value to state variables? Sorry for mistakes I made explaining it. JUST A BEGINNER! THANK you everyone!
Alt Text

Top comments (8)

Collapse
 
bihan001 profile image
Bihan Chakraborty • Edited

Instead of having an object as the state, use an array in the state and set the whole data array to it like setState({recievedArr: response.data data}) Then later you can use the state array and map function over it to render elements. like this.state.recievedArr.map(m=><p>{m.Company}</p>)

Collapse
 
yoqub98 profile image
yoqub98
Collapse
 
mathewthe2 profile image
Mathew Chan • Edited
const data = response.data.data.map(item=>{ 
  return {Date: item.Date, Company_nm: item.Company}
});
this.setState({data}) ;
Enter fullscreen mode Exit fullscreen mode

I'm only guessing what you want to do here.

Collapse
 
yoqub98 profile image
yoqub98

I somehow get what you did...except this.setState({data});
Then how I am going to be rendering this in my table? Could clarify that part too?

Collapse
 
mathewthe2 profile image
Mathew Chan • Edited

this.setState({data}) is shorthand for this.setState({data: data}), i.e. you assign the value of data to this.state.data. To render the data to your table

render() {
  const {data} = this.state;
  return (
    <table>
    <tr>
      <th>Date</th>
      <th>Company<th/>
    </tr>
    data.map(item=>return(
      <tr>
        <td>{item.Date}</td>
        <td>{item.Company_nm}</td>
      </tr>
    ))
    </table>
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pranav2612000 profile image
Pranav Joglekar

Yup. I would do something as done by Mathew Chan.
I use mui-tables, for displaying the data in tables. It allows me to just pass an object to the table component, without needing to worry about the minute details.
Reach out if you want to know more. I'll be happy to help

Collapse
 
pomfrit123 profile image
***

First, I dont do React, but will try something.
So the state variable will hold an array of objects?
[ { Date, Product, ..} , { Date, Product, .. } ]
Is it this what you want?

Collapse
 
kamo profile image
KAIDI

before the setState you can prepare your object first by looping over response then finally put your object in the state.