Joe Consterdine
Joe Consterdine

Reputation: 1053

React - Form submit + set state

in my to do list I'm having issues with the edit method.

I have a form with an input and submit button, when you first submit the form everything works fine, however when you try to do it the second time it appears to refresh the page despite having preventDefault on the method.

I tried removing the defaultValue but that didn't work.

Edit method

editedData(e) {
    e.preventDefault();
    let editedValue = this.editedData.value;
    let objectKey = this.props.data.key;
    let userId = firebase.auth().currentUser.uid;
    let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
    dbRef.update({
        value: editedValue
    })
    this.setState({
        editing: false
    })
}

Form

if(this.state.editing) {
    editingTemplate = (
        <form onSubmit={this.editedData}>
            <input className="form-input" type="text" defaultValue={this.props.data.value} ref={ref => this.editedData = ref} />
            <input type="submit" value="Save" />
        </form>
    );
}

Upvotes: 1

Views: 1382

Answers (2)

Kalaikumar Thangasamy
Kalaikumar Thangasamy

Reputation: 564

You are using this.editedData as method and ref object variable so it will overwrite function to object reference. Here I have changed this.editedData1 now you can get the data. Try this let me know if you have any issues.

if(this.state.editing) {
    editingTemplate = (
        <form onSubmit={this.editedData}>
            <input className="form-input" type="text" defaultValue={this.props.data.value} ref={ref => this.editedData1 = ref} />
            <input type="submit" value="Save" />
        </form>
    );
}

editedData = (e) => {
  e.preventDefault();
  let editedValue = this.editedData1.value;
  let objectKey = this.props.data.key;
  let userId = firebase.auth().currentUser.uid;
  let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
  dbRef.update({
    value: editedValue
  })
  this.setState({
      editing: false
  })
}

Upvotes: 2

Josh Alexy
Josh Alexy

Reputation: 411

The function is never actually called because it's not bound to the component. Since the function is being called on the form submit event, the this context is not your component. You have two options. If you have ES7 class properties enabled, you can do the following:

editedData = (e) => {
  e.preventDefault();
  let editedValue = this.editedData.value;
  let objectKey = this.props.data.key;
  let userId = firebase.auth().currentUser.uid;
  let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
  dbRef.update({
    value: editedValue
  })
  this.setState({
      editing: false
  })
}

Which binds the this context to the component.

Otherwise you can bind it in the constructor:

constructor() {
  super();
  this.editedData = this.editedData.bind(this)
}

Upvotes: 1

Related Questions