0

I'm trying to call a setState function inside of a _.map loop, but the loop lost the property 'this', and I can't use setState on this because this=undefined

  cargaDinamica(){

    _.map(this.state.redis, function(cache){
      obj.url = 'http://localhost:7000/viewlogredis';
      ServiceOS(obj)
      .then(retorno => {
        console.log("aaaa", this);
        view = retorno;
         this.setState({log : view});
      })
      .catch(err => {throw new Error(err)});


    obj = {url : 'http://localhost:7000' + cache.WebService,
            IPRedis: cache.IPDBMaster,
            WebService: cache.WebService,
            log : log};
    console.log("CARGA: ", obj);
     ServiceOS(obj)
       .then(function(carga) {
         console.log('CHEGOU AQUI');
         console.log("OK");
       })
       .catch(err => {throw new Error(err)});


    });

  },

this is my react function /\

2 Answers2

0

You need to change out this part

function(cache)

With

(cache) =>

Function will bind it to its scope, while an arrow function will bind to the this in the context where it was declared.

DevNebulae
  • 4,566
  • 3
  • 16
  • 27
0

Assuming this is inside a class extending React.Component, you can bind the lexical this inside the class's constructor:

class YourClass extends React.Component {
  constructor(props) {
    super(props);
    this.cargaDinamica = this.cargaDinamica.bind(this);
  }

  cargaDinamica() {
    your method here
  }

This will ensure that "this" points to the class scope inside your method, as it appears you intend.

Donny West
  • 710
  • 3
  • 6