TypeError: Cannot read property ‘setState’ of undefined

Bind the callback function also so that this inside the callback points to the context of the React Component and not the callback function

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: (data) => {
            this.setState( { posts: data } )
        }
    });
}

or you could use bind like

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState({ posts: data })
        }.bind(this)
    });
}

Leave a Comment