amos-baron
amos-baron

Reputation: 87

TypeError: Cannot read property 'groupsUrl' of undefined

Trying to make a my states to update from my db api every 5 seconds but i get an error that the state is not defined even tho it is.

I know that setState is asynchronous but in componentDidMount it can read the state so by my logic if componentDidMount calls reSetStates it is sure to be able to read the state.

class Groups extends Component {
  state = {
    groups : {},
    categories : ["id", "name", "last fault", "active"],
    groupsInfoList : [],
    enabledGroupsInfoList : [],
    disabledGroupsInfoList : [],
    groupsUrl : 'http://my.api.server/groups'
  }

  componentDidMount() {
    fetch(this.state.groupsUrl)
    .then(res => res.json())
    .then((data) => {
      var groups_object = data['result']
      this.setStates(groups_object)
      this.reSetStates()
    })
    .catch(console.log)
  }

  reSetStates(){
    fetch(this.state.groupsUrl)
    .then(res => res.json())
    .then((data) => {
      var groups_object = data['result']
      this.setStates(groups_object)
    })

    .catch(console.log)

    setTimeout(this.reSetStates, 3000);
  }

Upvotes: 1

Views: 26

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

It's binding issue , Change this

reSetStates(){

To:

reSetStates = () => {

Upvotes: 1

Related Questions