Thursday, 23 June 2016

javascript - Cannot read property setState of undefined

I'm having a react component, which has a function with a axios call, to retrieve data.
That data is being put into an array, and that array is being send to the state.




However, when trying to set I get the error:
Cannot read property 'setState' of undefined



I have bind the function in the constructor, and the setState is outside the axios call.



My code:



import * as React from "react";
import * as ReactDOM from "react-dom";


import axios from "axios";
import { host } from "../../searchkitConfig/const_host.js";

import {
SearchkitComponent
} from "searchkit";

export class AutoCompleteContainer extends SearchkitComponent {
constructor(props){

super(props);
this.state = {
"suggestCallReady" : false,
"suggestions":[]
};
this.suggestCall = this.suggestCall.bind();
}
suggestCall(){
const query =
{

"_source": [
"suggest-auteur"
],
"suggest": {
"auteur_suggest": {
"prefix": "te",
"completion": {
"field": "suggest-auteur"
}
},

"hoofdtitel_suggest": {
"prefix": "te",
"completion": {
"field": "suggest-hoofdtitel"
}
},
"imprint_suggest": {
"prefix": "te",
"completion": {
"field": "suggest-imprint"

}
}
}
};

var suggestArray = [];
axios
.post(host + "/_search", query, {
headers: {
"Content-Type": "application/json"

}
})
.then( res => {
for(var i = 0; i < res.data.suggest.auteur_suggest[0].options.length; i++){
suggestArray.push(res.data.suggest.auteur_suggest[0].options[i].text);
}

});
console.log('suggestArray:',suggestArray)
this.setState({"suggestions":suggestArray});

}
componentDidMount(){
this.suggestCall();
}
render(){
return(
{this.state.suggestions.length >1 ? this.state.suggestions : "No suggestions has been found"}

)
}
}



enter image description here

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...