This problem caused me a headache. this
keyword when you set a state is not accessible inside the ajax call
.
I think i miss-understand something in how react components work.
How should i use this
keyword in this specific situation as provided below? and in general if this
is not accessible.
class PollsList extends Component {
constructor() {
super();
this.state = {
polls: []
}
}
componentDidMount() {
$.ajax({
url: "/mypolls",
type: 'get',
dataType: 'json',
contentType: 'application/json',
success: function (polls_list) {
console.log(polls_list);
for (let i = 0; i < polls_list.length; i++) {
let data = polls_list[i].poll[0];
this.setState(()=>{polls:data});
}
},
error: function (err, status, xhr) {
console.log(err);
}
});
}
render() {
return (
<Fragment>
<div class='container'>
<ul id='polls_list'>{this.state.polls}</ul>
</div>
</Fragment>
)
}
}
EDIT: PROBLEM SOLVED!
Thanks for everyone contributed.
class PollsList extends Component {
constructor() {
super();
this.state = {
polls: []
}
this.fetchPolls = this.fetchPolls.bind(this);
}
componentDidMount() {
$.ajax({
url: "/mypolls",
type: 'get',
dataType: 'json',
contentType: 'application/json',
success: (polls_list)=>this.fetchPolls(polls_list), // this must look like that.
error: (err, status, xhr) =>{
console.log(err);
}
});
}
fetchPolls(polls_list){
for (let i = 0; i < polls_list.length; i++) {
let data = polls_list[i].poll[0];
this.setState({polls:data});
}
}
render() {
console.log(this.state.polls);
return (
<Fragment>
<div className='container'>
<ul id='polls_list'>{this.state.polls.option1} {this.state.polls.option2}</ul>
</div>
</Fragment>
)
}
}