Lucas Deane
Lucas Deane

Reputation: 3

React setState not updating array in state

I am trying to simply pull from this users API and put the array into the users variable in state. I am then printing it in componentDidMount(), but it prints as 'undefined'.

state = {
      users: [],
    }


  componentDidMount() {
    this.getCaseCount();
    console.log(this.state.users);
  }

//CoronaVirus API Goes here
getCaseCount(){
  fetch(`https://jsonplaceholder.typicode.com/users`)
  .then(response => response.json())
  .then(data =>
    this.setState({
      users: data,
    })
  )
}

Upvotes: 0

Views: 161

Answers (2)

Shaurya Vardhan Singh
Shaurya Vardhan Singh

Reputation: 684

On mounting of your component getCaseCount() is called and its fetching the data from

https://jsonplaceholder.typicode.com/users

while waiting for the response from API it moves on to the next part and logs the state but at this time the state is not updated as data has not been received, so it shows initial value of state which is an empty array.

Once the response from API is received the component is rerendered but componentDidMount runs only once hence you cannot see the updated state in it.

To see updated state write console.log(this.state) in render.

state = {
      users: [],
    }


  componentDidMount() {
    this.getCaseCount();
    console.log(this.state.users);
  }

//CoronaVirus API Goes here
getCaseCount(){
  fetch(`https://jsonplaceholder.typicode.com/users`)
  .then(response => response.json())
  .then(data =>
    this.setState({
      users: data,
    })
  )
}

render{
   console.log(this.state.users)
}

Upvotes: 2

Shohin
Shohin

Reputation: 558

It works fine. Try to put console.log inside render(), you'll see the array has something.

In your componentDidMount the data takes some time to get fetched which is why it shows an empty array initially.

Upvotes: 1

Related Questions