0

I try set a new value state like this on my render():

        this.state.contributionsList.map(function(item, i) {
            this.setState({
                listUsers: item.login
            })
        });

Also did like this:

let usersByRepo = this.state.contributionsList.map(function(item, i) {
    this.setState({
        listUsers: item.login
    })
});

If I run console.log(item) I have all my itens that I need. But If I add this information to my state, I get as feedback that my TypeError: Cannot read property 'setState' of undefined. Why?

I have intention to do it, because I will send this result as a prop to my component. But I still with this problem.

  • 1) Why this happen?
  • 2) What is the best method to solve this?
Cesar Cabral
  • 331
  • 4
  • 13
  • *"because I will send this result as a prop to my component."* Which result? `this.setState` doesn't return anything. – Felix Kling Nov 02 '17 at 00:08

2 Answers2

2

You should never call setState inside the render function, it will cause and infinite loop. Rethink your logic and put that code somewhere else and it will work.

Kutyel
  • 8,575
  • 3
  • 30
  • 61
0

Any new function() redefines what this is. If you can use ES6 fat arrow functions, do this:

this.state.contributionsList.map((item, i) => {
    this.setState({
        listUsers: item.login
    })
});

If not, this:

var that = this;
this.state.contributionsList.map((item, i) => {
    that.setState({
        listUsers: item.login
    })
});

That said, setting state in render() is definitely not something you want to do. It will result in an infinite loop, because setState() results in render() being called. I'm not sure what you're trying to do, but there should be a different way to do it.

Alastair
  • 5,894
  • 7
  • 34
  • 61