1

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?

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48

2 Answers2

0

There are two solutions for this,

Change your getDetails function definition to arrow function syntax

getDetails = () =>  {
  ... all the above code
}    

OR in constructor, bind this to getDetails function

this.getDetails = this.getDetails.bind(this);
Gangadhar Gandi
  • 2,162
  • 12
  • 19
0

Pass the forEach second argument this. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).

relatedsub.forEach(function(item, index) { //... }, **this**);
Siva K V
  • 10,561
  • 2
  • 16
  • 29