React: Call this.setState from Another Function

Re: Call this.setState from Another Function at:

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-22-react-part-ii/modules/wdcp-22-components-interacting/lessons/this-state/exercises/call-setstate-another-function

This is first example in the linked React documentation of avoiding having to manually bind the handler function.

The code below does not work in CodePen. The second alternative using an arrow function to call the handler does work. In the code below, the handleClick method does not get called when clicking the button. Can someone see what is wrong? This was copied and pasted directly from the React documentation. I only added the last two lines.

//html
<div id="root"></div>

//css
body {
    padding: 5px
}

//code
class LoggingButton extends React.Component {

  // This syntax ensures `this` is bound within handleClick. me: (this is a React doc comment)
  handleClick = () => {
    console.log('this is:', this);
  };
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<LoggingButton />);

Tried it and it works as expected :point_down:

That did not run earlier (button would not toggle) I went back to my code pen and it is running as expected. I hate when that happens because I do not know why. Thanks for the reply.

Here is another good learning opportunity React docs.

class Toggle extends React.Component {
	constructor(props) {
		super(props);
		this.state = { isToggleOn: true };

		// This binding is necessary to make `this` work in the callback
		//this.handleClick = this.handleClick.bind(this);
	}
        //The explicit binding is disabled.  What makes this work is making handleClick into an arrow function
	//see comment below on prevState
	handleClick = () => {
		this.setState((prevState) => ({
			isToggleOn: !prevState.isToggleOn
		}));
	};

	render() {
		return (
			<button onClick={this.handleClick}>
				{this.state.isToggleOn ? "ON" : "OFF"}
			</button>
		);
	}
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Toggle />);

// prevState: https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs
 According to the React docs "React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state."

// "To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument"

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.