Lalaluye
Lalaluye

Reputation: 71

React Native Redux: this.setState is not changing state

this.setState({device}) is not updating the state at all, unless I force it with "this.state.device = __" however it would still be a problem as the component does not re-render. I tried using a callback function such as:

this.setState({device: selectedDeviceId}, () => {
    console.log(this.state.device)
})    

but the code does not log at all, which indicates that setState is not even being called.

class Stats extends React.Component {
  state = {
    viewType: 'day',
    dt: moment(),
    device: {}
  }
  getDevice = () => {
    const devices = this.props.devices || []
    const selectedDeviceId = this.props.selectedDeviceId

    devices.forEach((d) => {
      if (d._id === selectedDeviceId) this.setState({device: d})
    })
    if (!this.state.device._id && devices.length) {
      this.setState({device: devices[0]})
    }
    this.getUsage()
  }

  componentWillMount () {
      console.log('Enter StatsScreen.componentWillMount')
      let dt = this.state.dt
      const date = moment(dt).format('YYYY-MM-D')
      console.log(date)
      this.getDevice()
  }
}

Upvotes: 0

Views: 578

Answers (1)

user9147922
user9147922

Reputation: 26

The problem is you're not using React Native state you're using a variable you've made called state. Fix this by writing the constructor lifecycle method and putting this.state = in there to initialise.

Btw avoid doing things like this in the willMount lifecycle method do it in the didMount then you're not blocking the UI.

Upvotes: 1

Related Questions