checkRaise
checkRaise

Reputation: 11

setState update value but displays old value

This simply displays an initial string. Then, when a button is clicked, it changes the string.

When run, though, it displays the initial string. Then, when the button is clicked, you can see the string change for a split second. (a log to the console of the new value is also triggered - and works). But, then the old string gets displayed again.

Why would it revert back if the change was made to the state?

Here is the code for displaying the string:

// Display.js
import React from 'react';

class Display extends React.Component {
    constructor(props) {
        super(props);
         this.state = {
            blogPosts: "The Bingham Blog"
        };
        this.clickHandler=this.clickHandler.bind(this);
    }

    clickHandler() {
        this.setState({
            blogPosts: "Changed!!!!!!!"
        }, () => {console.log(this.state.blogPosts)});
    }
    
    render() {
        return (
            <p>
                <form>
                    <button onClick={this.clickHandler}>Add on</button>
                </form>
                {this.state.blogPosts}
            </p>
        );
    }
}

export default Display;

Here is the App.js file that calls the <Display /> component:

import React from 'react';
import Display from "./Display";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Enter text for the blog</h1>
      </header>
    <div className="display">
        <Display />
      </div>
    </div>
  );
}

export default App;

I have been struggling with this for days. I know it is likely the asynchronous nature of setState, but I don't know how to fix it.

Upvotes: 1

Views: 721

Answers (2)

Tuhin
Tuhin

Reputation: 3373

The reason is if you have a <button> inside a <form>, when you click that <button> it will trigger submit action for that form.

So, you should provide type attribute to the button. type="button"

<button type="button" onClick={this.clickHandler}>Add on</button>

Upvotes: 1

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

Because your button is inside a <form> tag. By default on clicking the button, the form will submit and there will be a reload of the browser tab. That is why your state is reverted back to the initial state. Try moving your button out of that form. It should work.

Upvotes: 0

Related Questions