Reputation: 27
I am building pagination on my site and my 2nd setState method below comes back as not defined.
What am I doing wrong?
event.persist()
request('https://swapi.co/api/planets/?search='+event.target.value, (error,response,body) => {
this.setState({planetData: JSON.parse(body)});
let data = JSON.parse(body)
let numberOfPages = Math.ceil(data.count/10)
console.log(numberOfPages)
for(var i=1;i<=numberOfPages;i++) {
var div = document.createElement("button");
div.textContent = i
div.addEventListener('click', function(){
console.log('click')
request('https://swapi.co/api/planets/?search='+event.target.value+'&page=2', (error,message,body) => {
//this setState comes back as 'not a function'
this.setState({planetData: JSON.parse(body)});
console.log('body yay+'+body)
})
})
document.body.appendChild(div);
}
})
Upvotes: 1
Views: 232
Reputation: 130
You could use arrow functions when setting the state. For example
this.setState( () => {
return {
planetData: JSON.parse(body)
}
})
You can also access prevState as an argument if needed
this.setState( (prevState) => {....} )
which will give you access to the previous state in case you want to use that for manipulating the current state.
Setting state using an object, like you do, can cause problems because of its asynchronous character.Using arrow functions can solve this issue.
Always check where this refers to. An easy way to check it would be by using web dev tools and setting a break point in order to check if this refers to what you want it to refer or not.
Upvotes: 0
Reputation: 1187
Your this in the event listener refers to the element, not the this of the component. Try something like:
event.persist()
request('https://swapi.co/api/planets/?search='+event.target.value, (error,response,body) => {
this.setState({planetData: JSON.parse(body)});
let data = JSON.parse(body)
let numberOfPages = Math.ceil(data.count/10)
console.log(numberOfPages)
var me = this;
for(var i=1;i<=numberOfPages;i++) {
var div = document.createElement("button");
div.textContent = i;
div.addEventListener('click', function(){
console.log('click')
request('https://swapi.co/api/planets/?search='+event.target.value+'&page=2', (error,message,body) => {
//this setState comes back as 'not a function'
me.setState({planetData: JSON.parse(body)});
console.log('body yay+'+body)
})
})
document.body.appendChild(div);
}
})
Upvotes: 0
Reputation: 5133
You are using it inside div.addEventListener('click', function () {...})
.
So, this
inside the function does not have the same scope as your React Component.
You better use arrow function in addEventListener
.
div.addEventListener('click', () => {...})
Upvotes: 3