I am trying to fetch data from an API and setting it into the state by the setState
method, but I am getting an error:
TypeError: Cannot read property 'setState' of undefined at products.jsx:263
The code is:
getDetails () {
var subjectfinal = [];
let relatedsub = JSON.parse(subjects.related_subjects);
relatedsub.forEach(function(item, index) {
let formData = new FormData();
formData.append("subject_id", item.value);
fetch("https://***********/get_subject", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(responseJson => {
subjectfinal.push(responseJson[0])
console.log(subjectfinal) //gives me the subject data i,e array contaning 3 objects in it
this.setState({ subjectstobedisplayed: subjectfinal }),()=>console.log(this.state.subjectstobedisplayed)) // gives error
)
})
.catch(error => {
swal("Warning!", "Check your network!", "warning");
console.log(error);
});
});
};
I want to ask the if console.log(subjectfinal)
I am getting all the data then why at time of setting state it gives me error?