React functions on Glitch

I am following this Evernote clone tutorial and am trying to code on Glitch.

I am stuck about 45 minutes in.

Is there any reason why an update of state would not cause a re-render?
The state updates this.state.addingNote to true but seems to reset to false immediately.

I ask the question because the alert happens inside newNoteBtnClick function but the alert in the render doesn’t happen after the button click.

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import styles from './styles';
import List from '@material-ui/core/List';
import { Divider, Button } from '@material-ui/core';

class SidebarComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      addingNote: false,
      title: null
    };
  }

  newNoteBtnClick = () => {
    console.log('btn click', this.state.addingNote );
    var newState = !this.state.addingNote;
    alert(newState);
    this.setState = { addingNote : newState };
  }
  
  updateTitle = (txt) => {
    console.log('text is ', txt);
  }
 
  render() {
    //const { notes, classes, selectedNoteIndex } = this.props;
    const { classes } = this.props;
    alert('render' , this.state.addingNote);
    return(
      <div className={classes.sidebarContainer}>
        <Button onClick={this.newNoteBtnClick} className={classes.newNoteBtn}>
          { this.state.addingNote ? 'Cancel' : 'New Note' }
        </Button>
          { this.state.addingNote ? <div>adding</div> : <div>NOT adding</div> }
        <input type='text' className={classes.newNoteInput} placeholder='Enter title'
          onKeyUp={(e)=> this.updateTitle(e.target.value)}></input>
      </div>
    );
  }
}

export default withStyles(styles)(SidebarComponent);

setState is a method. You are attempting to assign an object to replace the setState method on this. I recommend:

newNoteBtnClick = () => {
  this.setState(prevState => ({ addingNote: !prevState.addingNote }));
}
1 Like