How to deal with this.setState issue in react JS

react setstate example
react setstate callback
react setstate function
this.setstate is not a function
react setstate prevstate
react setstate not updating
componentdidmount setstate
react native lifecycle

for some reason the value of my setState is not updating when I press the next button. It is for a progress bar where the progress bar adds 20 each time the button is pressed. So like value:this.state.value+20 Does anyone know whats going on? Any help is appreciated. Thanks!

import React, {Component} from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css"

class Questions extends React.Component {



     handleClick=()=>{
         alert(this.state.value);
         this.setState({
             value:this.state.value +20
         })


     }

    render() {

        this.state = {

            value:10
}

        return(
            <div>
                <div><Progress value={this.state.value} /></div>
                <div className="howMuchText">How much does it cost to build an app</div>


                <div className="nextButton">
                <Button onClick={this.handleClick} color="primary" size="lg">Next</Button>
                </div>
            </div>
        )
    }
}

export default Questions;

The reason this is not updating is because you are updating the state using setState in your handleClick function then reseting it in your render function so you are undoing your update. Try this.

Change your source from what you have to this:

import React, { Component } from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css"

//you've imported component so you don't need to do React.Component
class Questions extends Component {

   state = { 
     value: 10, 
   } 
     handleClick = () =>{
         alert(this.state.value);
         this.setState({
             value: this.state.value +20
         })
     }

    render() {

        return(
            <div>
                <div><Progress value={this.state.value} /></div>
                <div className="howMuchText">How much does it cost to build an app</div>


                <div className="nextButton">
                <Button onClick={this.handleClick} color="primary" size="lg">Next</Button>
                </div>
            </div>
        )
    }
}

This should do it. Hope this helps.

Why my setState doesn't work?, apply the new values to the state until the component is reconciled. The code above calls a this.setState function and passes in an object with key-value pairs. If the key matches one we already have in state, it updates the value in state to the new value provided. If the key matches one we already have in state, it updates the value in state to the new value provided.

changing state inside the render function is wrong. At every update, state is going to change. State is immutable at react. You can initialize it inside your constructor function.

  constructor(props) {
        super(props);
        this.state = {

            value:10
             }
       }

What happens when setState() function is called?, can think of as an object representation of your UI). A quick intro to setState in React.js How to use setState effectively and what pitfalls to avoid State management shouldn’t be like solving Rubik Cube :) TL;DR — In case you are a visual learner, head over to the video I made: ReactJS — How setState works. Or watch it here: An introduction to setState

You should use constructor to initialize the value. What are you doing wrong in your code when you click button it is updating the value but setState re-render the so it again to initialize value=10.

import React, {Component} from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css"

class Questions extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value:10
        }
   }


 handleClick=()=>{
     alert(this.state.value);
     this.setState({
         value:this.state.value +20
     })


 }

render() {

    return(
        <div>
            <div><Progress value={this.state.value} /></div>
            <div className="howMuchText">How much does it cost to build an app</div>


            <div className="nextButton">
            <Button onClick={this.handleClick} color="primary" size="lg">Next</Button>
            </div>
        </div>
    )
 }
}

  export default Questions;

React setState usage and gotchas, that this component and its children need to be re-rendered with the updated state. // this.setState(function(previousState, currentProps) { return { counter: previousState.counter + 1 }; }); This can be safer than using an object argument where multiple calls to setState() are used, as multiple calls may be batched together by React and executed at once, and is the preferred approach when using current props to set state.

How to become a pro with React setState() in 10 minutes, A React class component has an internal state which like props affects It doesn'​t matter how many setState() calls in how many components you For example, if child and parent each call setState() when handling a click  Component state is a way of holding, processing and using information that is internal to a given Component and allows you to implement its logic. State is usually a POJO (Plain Old Java[Script]…

Component State – React, State allows React components to change their output over time in response to When you setState a prop and use it in your component, you're breaking the We are setting state as an object, and there's no problem because our Then it calls the handleCounter to update the counter info, and in the end  Users new to React and setState() frequently encounter obstacles while trying to do things that just work with vanilla JS and direct DOM manipulation. React is designed to make it easier to build

State and Lifecycle – React, setState() schedules an update to a component's state object. This would break the consistency between props and state , causing issues that are very hard to  Then you run into GC and memory issues, and blame React for being slow. This is especially critical on mobile devices where memory issues can cause a browser to crash. There are two types of callbacks.

Comments
  • Why do you have this.state = { value: 10} inside of your render? That’s the cause of your issue and not something you are supposed to do.
  • That was just default. Sorry, Im pretty new to this
  • Take the time to go through some beginner React tutorials before asking a question here. This type of question is not really helpful to others and is easily debugged (akin to a typo). To explain: That’s not how you default state in React. You have to do it in the constructor or by using the class field declaration shortcut. By doing that in render, value will always be 10.
  • i don't think this question should have been down voted it discourages people from asking questions :( kenny335 may have done tutorials and none of them explained this...but im a newbie to stack overflow so maybe im wrong :)
  • np happy coding :)
  • you no longer need constructor...the code will still execute with it but you don't need it save your fingers some typing :)
  • @BensSteves I know but this is the proper way to initialize your variable in react when you will have more numbers of state then it will be difficult for you to manage state without constructor.
  • I'm not sure I quite agree with that. Imagine you have five methods that you have to constantly bind to your component just bc your using the constructor route. I think you can manage the state just as well without. Just my opinion. i do think your way is good for beginners though. Gives them a better understanding. and plus I think there's more documentation for your way :)
  • I agree but I am talking about code quality and it will be easy for developer to understand the problem when they will get bugs in their code.
  • ah yes I agree with you