I'm trying to write a component in React that will use the fetch() API to get data from a website, then use setState to set a state equal to the data, and then finally render the data. My code looks like this:
import React from 'react';
export default class Test extends React.Component {
constructor(props){
super(props);
this.state = {apiInfo: 'default'};
}
componentDidMount(){
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(
function(response){
return response.json();
}
).then(function(jsonData){
return JSON.stringify(jsonData);
}
).then(function(jsonStr){
this.setState({apiInfo: jsonStr});
console.log(jsonStr);
});
}
render(){
return(
<tr>
<td>{this.state.apiInfo}</td>
</tr>
);
}
}
However, this results with an error saying I'm unable to setState of undefined. I end up rendering 'default' on my HTML. What exactly am I doing wrong here?