0

I'm new to react, and when I try to fetch data from API I get the error of this:

"TypeError: this.state.data.map is not a function".

I am just following the tutorial on YouTube, but why I can't get the result? Anyone of you please help me to fix this issue. Consider the code below:

The JSON response from api should be like this : enter image description here

constructor(props){
  super(props);
  this.state ={
    loginEmail: this.props.location.state.loginEmail,
    data: [],
    user_info: [],
    isLoaded: false,
    redirect: false
  }
  this.logout = this.logout.bind(this);
}

componentDidMount(){
 //  console.log(this.state.loginEmail)
  fetch(`https://ems-unimas-58134.herokuapp.com/api/users/view/${this.props.location.state.loginEmail}`)
  .then((resp)=>{
    resp.json().then((res)=>{
      //console.log(res.data.user_info);
      this.setState({data: res.data.user_info})
;    })
  })
}
  render(){

    if(this.state.redirect){
      return (<Redirect to ={'/login'}/>)
    }
    //const data=this.state.data;
    //console.warn(data);
const data = this.state.data;    
//console.log("data: ", data)
    return (      
        <div>
            {
              this.state.data?
              this.state.data.map((item)=>
              <h3>{item.name}</h3>
              )
              :
              <h3>wait...data is fetching</h3>

            }
        </div>
    );
  }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
koko ka
  • 107
  • 4
  • 17
  • 4
    `map` is for arrays, you have an object. See https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays – Tim Feb 05 '20 at 05:18
  • You would have to change the conditional to `this.state.data && Array.isArray(this.state.data)` – freakomonk Feb 05 '20 at 06:26

0 Answers0