WTF WTF - 5 months ago 8
JSON Question

Object is undefined from within React Component

In my react component, I'm getting some data from a .json file. That data is teams and roles.

In my first for loop, I'm able to access team just fine...I don't get any errors. But when it hits my inner loop, I get role is undefined. I know for a fact that the role is fine in my json, but for some reason, the web page isn't interpreting it as an object I guess and not sure why.

Here is the component:

const TeamLocationsAndRoles = Component({
render(){
var company = this.props.company,
teams = company.interview.teamProfile.teams,
roles = company.interview.teamProfile.roles,
currentLocation,
locations = [];

for(let team of teams){
currentLocation = <span className="ink-badge bold orange font-black">{team.location.city}</span>;

currentLocation += <ul>;
for(let role of roles){
currentLocation += <li>{role.total}<span className="ink-badge black small">{role.title}</span></li>
};
currentLocation += </ul>;

locations.push(currentLocation);
currentLocation = null;
}

return(<div>{locations}</div>)
}
});


Here is how I'm passing the data to that component:

const TeamProfile = Component({
store: Store('/companies'),
render(){
var company = this.store.value()[this.props.companyId];

return (
<div id='ft-team-profile className="all-100"'>
<p className="section-heading bold padding-top-20 font-22">Team Profile</p>
<div className="all-100 padding-left-30 align-left">
<div>
<span className="bold blue">Locations & Roles</span>
<p className="padding-top-20 padding-left-30">
<TeamLocationsAndRoles company={company}/>
</p>

</div>
)
}
});


And here is the related json (starting with teamProfile):

[{
"teamProfile": {
"teams": [{
"location": {
"city": "Chicago",
"state": "Illinois"
},
"roles": [{
"title": "UX",
"total": 1
}, {
"title": "Full-Stack Engineer",
"total": 3
}, {
"title": "Front-End Engineer",
"total": 4
}, {
"title": "Backend Engineer",
"total": 2
}]
}, {
"location": {
"city": "San Francisco",
"state": "California"
},
"roles": [{
"title": "Full-Stack Engineer",
"total": 2
}]
}]
}
}]

Answer

The JSON file in your post has a teamProfile.teams, but not a teamProfile.roles. It looks like each team has a roles property though, perhaps that is what you were looking for?

render(){
    var company = this.props.company,
        teams = company.interview.teamProfile.teams,
        currentLocation,
        locations = [];

    for(let team of teams){
        var roles = team.roles;
        currentLocation = <span className="ink-badge bold orange font-black">{team.location.city}</span>;

        currentLocation += <ul>;
            for(let role of roles){
                currentLocation += <li>{role.total}<span className="ink-badge black small">{role.title}</span></li>
            };
            currentLocation += </ul>;

        locations.push(currentLocation);
        currentLocation = null;
    }

    return(<div>{locations}</div>)