State is being updated infinitely - React

State is being updated infinitely - React
0.0 0


Hey, I’m working on the toggle between celsius and fahrenheit, this is the method I’m trying to use:

temperature(e, unity) {
      isCelsius: unity

    if (this.state.isCelsius) {
      return (this.state.celsius);
    } else {
      return (this.state.fahrenheit);

However, it seems like it’s being called forever, but my implementation is the following:

<i className="wi wi-celsius" onClick={e => this.temperature(e, true)}></i> | 
<i className="wi wi-fahrenheit" onClick={e => this.temperature(e, false)}></i>

And I initialize my state isCelsius to false:

this.state = {
  loading: true,
  isCelsius: true

And this is the error:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

What could it be?


I’m not quite sure but I think it might be the calling of the temperature method within the render method

try moving it into the componentWillMount function.

If that doesn’t work please provide a codepen with all your code and I’ll be glad to figure the issue put for you. Good luck!


I ended up using the operator ? (I always forget it’s name)

{isCelsius ? celsius : fahrenheit}
<i className="wi wi-celsius" onClick={e => this.setState({isCelsius: true})}></i> | 
<i className="wi wi-fahrenheit" onClick={e => this.setState({isCelsius: false})}></i>