0

What I'm trying to do is, store a input field value to a state and then, If a user click on save button or store button then input field will be vanished so editing will be false.I'm trying to check the state length when user click on the save button. The problem is there. it's say's this error: Uncaught TypeError: Cannot read property 'state' of null, But I've already stored data on editData state why is that please can you tell me?

Here is Codes to understand better

class EditData extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {
            editData: ''
        }
    }
    handleChange(e) {
        this.setState({editData: e.target.value})
    }

    save() {
        if (this.state.editData.length !== 0) {
            this.setState({isEditing: false});
            console.log(this.state.editData + 'Added on your database')
        } else {
            alert('Hahah Are you')
        }
        // console.log(this.refs.valTo.value);
    }
    render() {
        return (
            <div>
                <input onChange={this.handleChange} type="text" defaultValue={this.props.data}  /> <button onClick={this.save}>Save</button> <button>cancel</button>
            </div>
            );
    }
}
Code Cooker
  • 881
  • 14
  • 19
  • Possible duplicate of [Reactjs component does not re-render after setState](https://stackoverflow.com/questions/43717638/reactjs-component-does-not-re-render-after-setstate) – Shubham Khatri Jun 04 '17 at 17:55

1 Answers1

5

You need to bind handleChange and save. Check also that you initialized state in the constructor.

In the constructor do:

this.handleChange = this.handleChange.bind(this);
this.save= this.save.bind(this);
this.state = {};
Bugs
  • 4,491
  • 9
  • 32
  • 41
Mayday
  • 4,680
  • 5
  • 24
  • 58