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 :
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>
);
}
}