Monday 26 September 2016

jquery - "TypeError: Cannot read property 'setState' of undefined" when reading JSON into state

I know this question has been asked before, but I've tried all the suggested solutions and none of them work (which might, admittedly, be down to me being a numpty).



Anywho, my particular problem is that the following line is causing the error ('TypeError: Cannot read property 'setState' of undefined'): this.setState({pictures : response, loading: false});



FWIW, the previous line is a console.log call that tells me that the response has come back OK.



Here's the code in its entirety:



import {Component} from 'react'
import fetch from 'isomorphic-fetch'

import {Checkbox, CheckboxGroup} from 'react-checkbox-group';
import Thumbs from './Thumbs';



class Search extends Component {



constructor(props) {
super(props)
this.state = {
loading: false,
images: false,

audio: false,
pictures: []
}
this.handleSubmit = this.handleSubmit.bind(this);
}

componentWillUpdate(nextProps) {
this.style = {backgroundColor: 'green'}
}


handleSubmit(e) {
e.preventDefault();
const search = e.target[0].value;
const vid = e.target[1].checked;
const aud = e.target[2].checked;

var medium = "image";

if (aud) {
medium = "audio";

}

var endPoint = "https://images-api.nasa.gov/search?q=" + search + "&media_type=" + medium;
console.log(endPoint);
fetch(endPoint)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();

})
.then(function(response) {
console.log(response);
this.setState({pictures : response, loading: false}); //PROBLEM IS HERE
});

}


render() {

const { pictures, loading } = this.state
function mediaChanged(newMedia) {
if (newMedia.length === 2) {
newMedia.shift();
}
};

return (

NASA Search






name="media"
onChange={mediaChanged}>











{(pictures.length) ?
pictures.map(
(pictures, i) =>

) :
-
}

)
}



}



export default Search

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...