I am attempting to use the setState function to set my 'plot' state to a json object 'data' in this callback function. I know the 'data' object is being passed in correctly because I am able to log it to console the line before my this.setState() call, however, when I attempt to set the state, I'm getting "TypeError: Cannot read property 'setState' of undefined." Here's the code:
constructor(props) {
super(props);
this.state = {
plot: null,
};
this.getPlot = this.getPlot.bind(this);
this.getPlot.fetchServiceData = fetchServiceData.bind(this);
}
getPlot() {
fetchServiceData('/plot', function (data) {
this.setState({plot: data}, function () {
if(this.state.plot) {
Bokeh.embed.embed_item(this.state.plot, 'AAPL_plot');
}else{
console.error('Unable to set plot state.')
}
});
});
}
componentDidMount() {
this.getPlot();
}
Here is my fetchServiceData function, in a different file that is imported:
function fetchServiceData(apiPath, callback) {
let data = null;
fetch(BASE_SERVICE_URL + apiPath)
.then(response => response.json())
.then(function(data) {
console.log(this)
callback(data);
})
.catch(error => console.log(error));
}
export { fetchServiceData };
Do I need to somehow bind 'this' to my fetchServiceData() function, or that function's callback?