1

I fetch data from my api, JSON is :

{
  Teacher: 53, 
  Student: 0,
  Staff: 1, 
  Finance: 0, 
}

My data are stored in my state when the component didMount so this.total.users contain my JSON data

What is the best way to render this ?

I understood it's JSON with keys, so I'm supposed to use something like

 {Object.keys(this.state.users).map((key) => (   
   <div> {key} </div>   // display Attendee, Student, Staff, Finance
 )} 

but its not working, because this.state.users is undefined So I found I can display my entire JSON object with, it works with

 JSON.stringify(this.state.users)}

So I supposed I have to mix both of them but how and when ? i'm a little bit lost.

at the end I just want to have my JSON displayed like:

Attendee   Student   Staff   Finance
   53         0        1        0

1 Answer 1

3

You can do something like below

  1. Do conditional check before doing Object.keys so there won’t be any issues when this.state.users is undefined
  2. Use key to get the value like this.state.user[key]
  3. Set the unique key to div so that you will get all the users rendered otherwise only the last one will be rendered

    {this.state.users && JSON.stringify(this.state.users, Object.keys(this.state.users).map((key, index) => (   
          <div key={'Key-'+index}>
              <div> {key} </div>   // display Attendee, Student, Staff, Finance
               <div>{this.state.users[key]</div> //this will give you value
           </div>
      )))} 
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer ! It works if I take your answer but without JSON.stringify(this.state.users, Do you know why ? I would like to understand, if you stringify it, it display {} but if I take juste {JSON.stringify(this.state.users)} it shows the entire object.

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.