Code Cooker
Code Cooker

Reputation: 939

State not working properly in ReactJS

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>
            );
    }
}

Upvotes: 0

Views: 180

Answers (1)

Mayday
Mayday

Reputation: 5146

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 = {};

Upvotes: 5

Related Questions