-1

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?

  • Possible duplicate of [React - uncaught TypeError: Cannot read property 'setState' of undefined](https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Anurag Srivastava Jul 27 '19 at 15:51

1 Answers1

0

The error is explicit : you can apply the method setState on undefined values.
Therefore you have to bind your context this to your method by calling .bind(this) on it.

cocool97
  • 1,201
  • 1
  • 10
  • 22
  • I am trying to implement your solution but having trouble getting it to work. I just attempted to bind it by stating: this.getPlot.fetchServiceData = fetchServiceData.bind(this); in the constructor but the context is not being carried over. Could you be a bit more specific with your answer please? Thanks for the help. – Adam Tamargo Jul 30 '19 at 22:11
  • Can you edit your post with the modification you carried? – cocool97 Jul 31 '19 at 02:27
  • I've added the modification as well as the function that is being called w/in getPlot. Let me know if there is any other info that would be helpful – Adam Tamargo Aug 05 '19 at 22:04