0

I'm working on react app, and I've called a backend to retrieve data. Data from backend is retrieved with res.status(200).json(user). That call in react is

import React, { useState, useEffect } from 'react';

import UserService from '../services/user.service';

const AdminBoard = () => {
  const [content, setContent] = useState('');

  useEffect(() => {
    UserService.getAdminBoard().then(
      (response) => {
        setContent(response.data);
      },
      (error) => {
        const _content =
          (error.response &&
            error.response.data &&
            error.response.data.message) ||
          error.message ||
          error.toString();

        setContent(_content);
      }
    );
  }, []);

  console.log(content);
  

  return (
    <div className='container'>
      <header className='jumbotron'>
        <h4>List of users</h4>
        {content &&
          content.map((item) => (
            <div key={item.username}>
              <div className='container p-3 my-3 bg-dark text-white'>
                <strong>Username:</strong>
                <h4>
                  <div>{item.username}</div>
                </h4>
                <strong>Email:</strong>
                <h4>{item.email}</h4>
                <strong>Role:</strong>
                <h4>{item.roles.name}</h4> //I'm not getting role name
              </div>
            </div>
          ))}
      </header>
    </div>
  );
};

export default AdminBoard;

Now when i console.log content i get:

0: {name: "New Name", username: "agent", email: "[email protected]", roles: Array(1)}
1: {name: "admin", username: "admin", email: "[email protected]", roles: Array(1)}
etc

How roles looks like when i expand them(sorry for picture I couldn't paste output here): console.log content and look of roles

Now I can easily get my values when I usecontent.map with item.name and integrate them into my code. But i have a problem when I try to extract value from roles. Now when i console.log content.roles i get undefined.

I want to get name from this array. But I've tried with many ways:

console.log(content.roles.name) console.log(content.roles['name']) console.log(content.roles[0].name) etc. I've also tried with few forEach loops that i found on StackOverflow but I always get cannot read property something of undefined.

My questions are:

  1. Is this an array of object or is it object with array of objects?
  2. Is there a method to access these values without loops?
5
  • roles is an array, so the console.log(content.roles[0].name) should be right. But the content is an Array too, so you must use content[0]... Commented Jan 19, 2021 at 14:00
  • @AlTheLazyMonkey TypeError: Cannot read property '0' of undefined. That's what i get by error. Belive me i'm staring in the code for like 1 hour and i don't get it why it won't let me access to the value. Ok maybe it needs to be looped with .map but why when i content.map still doesn't give me at least whole object? Commented Jan 19, 2021 at 14:03
  • in the callback of .map you have the a single element of the main array, this for example {name: "New Name", username: "agent", email: "[email protected]", roles: Array(1)}. In your example you can use a second map inside the first map on the roles array. Commented Jan 19, 2021 at 14:10
  • it works when i use item.roles[0].name inside a map. I don't need another .map. I also asked people below: How that [0] gives right role name? shouldn't retrieve role name inside [0] array? (in my example how doesn't set name PM for every single role?) Commented Jan 19, 2021 at 14:15
  • 1
    item.roles[0].name return correct value because roles is an array with a single element inside and you use [0] like index for retrieve the first and unique element Commented Jan 19, 2021 at 14:23

2 Answers 2

1

It looks like you have an array of objects in another array. So you need to access a given role name like this:

content[0].roles[0].name
Sign up to request clarification or add additional context in comments.

4 Comments

when i saw ur reply i tough THIS MUST work. BUT..... TypeError: Cannot read property 'roles' of undefined. EDIT: it works! But i need to put it inside content.map then use item.roles[0].name to display a name. Thanks for the solution. But one question. How that [0] gives right role name? shouldn't retrieve role name inside [0] array? (in my example how doesn't sate name PM for every single role?)
can you provide the exact line causing this error ?
it seems that each item in your list contains only one role in the roles array so ´roles [0]´ always returns that element
Thanks too, happy to have been able to help. It would be more appropriate all the same to make another map for the names of the roles since roles is an array, doing so you would obtain a more suitable code.
0

Is this an array of object or is it object with array of objects?

So content is an array of objects with each (so each user) an array of objects (roles) with (per your example) only one object in it.

Is there a method to access these values without loops?

Yes, if you know the indexes (key) you can, otherwise you have to search the array or indeed loop through. So if it is always just one then index 0 [0] would be fine so roles[0].name or roles[0].user_roles.roleId. if there could be multiple indexes in it you have to know the right one.

2 Comments

Thanks fore the answers! I also put this question on answer above: How that [0] gives right role name? shouldn't retrieve role name inside [0] array? (in my example how doesn't set name PM for every single role?)
@Aldinho Because [0] is the key index of that object WITHIN that ARRAY. So in your case roles is an array of objects with only 1 object so to access that you specify the key index, 0 [0] in this case

Your Answer

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