-1

I need to write to state information at each iteration of the script. How to do it correctly?

    getPageLink(i) {
        if(i > 0){
            console.log(this.state.res) // aaa
            new Promise((resolve, reject) => {
                request(this.props.catalogLinks[i], function (error, response, html) {
                    if (!error && response.statusCode == 200) {
                        var $ = cheerio.load(html);
                        $('.post__title_link').each(function (i, element) {
                            console.log(this.state.res) // undefined
                        });
                        resolve("result");
                    } else {
                        console.log('sss', this.state.res) // undefined
                        reject("result");
                    }
                });
            }).then(
                result => {
                    this.getPageLink(--i)
                },
                error => {
                    this.getPageLink(--i)
                }
            );
        }
    }

Now in the console:

aaa

bundle.js:53444 Uncaught TypeError: Cannot read property 'res' of undefined

How to fix the error?

full code

VINET
  • 641
  • 1
  • 7
  • 28

2 Answers2

0

this is being overwritten in the callback. You should put its value into another variable like so:

var that = this;

And then use that from then on:

    getPageLink(i) {
        if(i > 0){
            console.log(this.state.res) 
            var that = this;
            new Promise((resolve, reject) => {
                request(this.props.catalogLinks[i], function (error, response, html) {
                    if (!error && response.statusCode == 200) {
                        var $ = cheerio.load(html);
                        $('.post__title_link').each(function (i, element) {
                            console.log(that.state.res)
                        });
                        resolve("result");
                    } else {
                        console.log('sss', that.state.res)
                        reject("result");
                    }
                });
            }).then(
                result => {
                    this.getPageLink(--i)
                },
                error => {
                    this.getPageLink(--i)
                }
            );
        }
    }
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
0

You have to use the arrow notation () => {} when defining the callback function:

request(this.props.catalogLinks[i], (error, response, html) => {
       if (!error && response.statusCode == 200) {
          var $ = cheerio.load(html);
          $('.post__title_link').each((i, element) => {
              console.log(this.state.res) // will be defined
          });
          resolve("result");
       } else {
          console.log('sss', this.state.res) // will be defined
          reject("result");
       }
});
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149