1

This is the issue I'm facing, it works fine outside componentDidMount and return the exact number when called in a function after render the views:

componentDidMount = () => {    
  var obj = snapshot.val()
  var favoritesList = []
  var keys = []

  for(let a in obj){
    favoritesList.push(obj[a])
    keys.push(a)
  }

  this.setState({
    favoritesList:favoritesList,
    keys:keys,
  })

  console.log(this.state.keys.length)
  console.log(this.state.favoritesList.length)
}

My goal is to show a text component when list is empty like so

  if (this.state.favoritesList.length === 0)
      this.setState({empty: true})

      ...

      {this.state.empty ?  
        <Text>
         Oh such empty!
        </Text>
         : null }

When calling this function it works, I am little bit confused:

test(item) {
    console.log(item.index)
    console.log(this.state.keys.length)
}

1 Answers1

3

setState is asynchronous. This means that in order to access the latest, one needs to do it inside callback:

 this.setState({
   favoritesList,
   keys,
 }, () => {
   console.log(this.state.keys.length)
   console.log(this.state.favoritesList.length)
 });

And if I interpreted your code correctly, you're calling setState inside render() which is definitely NOT acceptable.

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
  • so I only have to add this () => and put my function inside brackets {} to access the latest? I don't see what setState you talking about? It's working btw, thanks –  Sep 24 '18 at 08:31
  • @blvckasvp I think zvona meant that you're calling setState directly inside render instead of using a function which would do it. [This](https://stackoverflow.com/questions/31702861/when-value-is-assigned-to-components-state-why-console-log-prints-the-previous) should help you with the first part ;) – ppu Sep 24 '18 at 08:39