React - what's the problem with my code?

export default class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        counter: 25,
      }
      this.handleClickTest = this.handleClickTest.bind(this);
    }
    handleClickTest() {
        for(let i=25;i>=0;i--){
            this.setState({counter: this.state.counter-1});
        }
    }

    render() {
        return (<div> {this.state.counter}
            <form>
                <button onClick={this.handleClickTest}>start</button>
            </form>
          </div>
        );
    }
}

I trimmed to code to the bare minimum for your convenience. When I click ‘start’ the counts changes to 24 and nothing happens more. Why does it not continue counting down?
EDIT: it seems to me after the counter displays 24 the page “refreshes”.

Try to remove this from this.state.counter.
this.setState({counter: state.counter - 1})

'state' is not defined  no-undef

I tried. Doesn’t compile.

When a form only has a single button in it and it is clicked, the default action is for the form to try and submit. Since your form does not have an action attribute telling where to submit the form, it attempts to submit to itself and Codepen does not allow this, which is why you get an error. See if you can do some research on how to prevent the default action of submitting the form.

The reason you only see it go to 24 is that you are not using the functional version of the setState method. I suggest doing some more research on this topic.

1 Like

Removing the form element makes it count down to 24 without refreshing. I still don’t understand what’s wrong with using the setState method the way I did since it’s almost the same as in the EDX React course example…

 handleClickTest(e) {
    e.preventDefault();
    this.setState((state) => ({
      counter: state.counter + 1,
    }));
  }

I tried this code and it works.

Just add this in your handleClickTest fx e.preventDefault() to avoid the page to refresh.

handleClickTest = (e) => {
    e.preventDefault()
      for(let i=25;i>=0;i--){
          this.setState({counter: this.state.counter-1});
      }
  }

@Bam92 @AmaliaTadevosyan Instead of just giving away the code solution, try to just give hints. It is easy to just post a code that works. It is much better for the user to use hints and suggestions to figure it out on his/her own. The user would learn more from the exercise.

4 Likes

What’s with </View> ?
I believe it should be <View/>

I agree with you. Maybe a typo?

Amalia,
Your code was the only one that worked. Bam92’s code only counted to 24. Removing the ‘this’ gave an error. I don’t understand why your code worked without and why would using an anonymous function make a difference.

It is working well on my side. Just make sure you write it well (arrow function).

See the last comment in my reply above.

1 Like