I was getting an error that state was undefined in this component class method although it was set.
// searchState undefined error
fetchSearchImages() {
const { searchStart, count, term, searchImages } = this.state;
this.setState({
searchStart: searchStart + count
});
axios
.get(`/api/photos/search?term=${term}&count=${count}&start=${searchStart}`)
.then(res =>
this.setState({
searchImages: searchImages.concat(res.data.results)
})
);
}
However, changing it to an arrow function (class field declaration syntax) resolved the error and my code worked as expected.
// No more error
fetchSearchImages = () => {
const { searchStart, count, term, searchImages } = this.state;
this.setState({
searchStart: searchStart + count
});
axios
.get(`/api/photos/search?term=${term}&count=${count}&start=${searchStart}`)
.then(res =>
this.setState({
searchImages: searchImages.concat(res.data.results)
})
);
}
Why can't I use ES6 class method shorthand for this? My guess is it's something to do with having to bind, but I didn't know I needed to bind in that scenario.