1

I have a react web app that is fetching a JSON object from my API on componentDidMount().

I am able to view the data in React dev tools in web browser but i am having trouble mapping the data to HTML. I have done it this way in previous applications but its not working with my current object.

I am sure there is a small problem with the syntax of how I am mapping the array. Thanks for the help.

image of data object from react tools

import React from "react";
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

class TeamInformation extends React.Component{
state = {teamNames: []}

constructor(props) {
    super(props);
    this.state = {
        selectedTeam: "none"            
    };
}

componentDidMount(){
    fetch('/users/teamNames')
    .then(res => res.json())
    .then(teamNames => this.setState({teamNames}));
}

render(){

return (
<div>
    <h1>Teams</h1>

{this.state.teamNames.map(teamData =>
    <div key={teamData.PK_TeamID}>
        <p>{teamData.cityName}</p>
    </div>
)}
</div>
)}}

export default TeamInformation;

1 Answer 1

1

As I see in your attached image, the state teamNames is an object instead of array. You couldn't map an object, just change your code to this:

constructor(props) {
    super(props);
    this.state = {
        selectedTeam: "none",
        teams: []            
    };
}

componentDidMount(){
    fetch('/users/teamNames')
    .then(res => res.json())
    .then(teamNames => this.setState({teams: teamNames.teamData})); // teamData is an array, not teamNames
}

render(){
    ...
    {this.state.teams.map(team=>
        <div key={team.PK_TeamID}>
            <p>{team.cityName}</p>
        </div>
    )}
}
Sign up to request clarification or add additional context in comments.

3 Comments

I changed it as you said to be: render(){ return ( <div> <h1>Teams</h1> {this.state.teamNames.teamData.map(team=> <div key={team.PK_TeamID}> <p>{team.cityName}</p> </div> )} </div> )}} But now it says: TypeError: cannot read property 'teamData' of undefined.
Take a look at my answer, I have updated constructor and componentDidMount
@PringlerRushing does is help? Do you have any problem?

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.