Save React form values to firebase real time database

All we need is an easy explanation of the problem, so here it is.

I have done this code it shows console output properly on writing console.log() method but it doesn’t store code to my database.

It doesn’t shows any other errors but don’t store data to database, so please tell me what to change to make to store to database.

Here is the code :

import React, { Component } from 'react';
    var firebase = require('firebase');
    var uuid = require('uuid');

    var config = {
        apiKey: "AIzaSyDf5i7ULK0JTWYM3_X3wMQPUaaLPRYExC0",
        authDomain: "usurvey-419eb.firebaseapp.com",
        databaseURL: "https://usurvey-419eb.firebaseio.com",
        projectId: "usurvey-419eb",
        storageBucket: "usurvey-419eb.appspot.com",
        messagingSenderId: "395101866940"
      };
      firebase.initializeApp(config);
    class Usurvey extends Component {
      constructor(props)
      {
        super(props);
        this.state={
          uid:uuid.v1(),
          firstName: '',
          lastName:''
        };
        this.submitData=this.submitData.bind(this);
        this.inputData=this.inputData.bind(this);
      }
      submitData()
      {
        document.write({uid: this.state.uid,firstName:this.state.firstName,lastName:this.state.lastName});
        // document.write(this.state.firstName);
        // document.write(this.state.lastName);


        firebase.database().ref('Newdata/'+this.state.uid).set({
          firstName: this.state.firstName,
          lastName: this.state.lastName
        });
      }
      inputData(event)
      {
        var firstName = this.refs.name1.value;
        var lastName = this.refs.name1.value;
        console.log(this.state.uid,this.state.firstName,this.state.lastName);

        this.setState({firstName:firstName, lastName:lastName});
        console.log(this.state.firstName,this.state.lastName);
      }
      render(){
        return(
          <div>
            <form onSubmit={this.submitData}>
              <input type="text" onChange={this.inputData} ref="name1"/>
              <input type="text" onChange={this.inputData} ref="name2"/>
            <input type="submit" />Submit
            </form>
          </div>
        );
      }
    }
    export default Usurvey;

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

When you submit a form you have to prevent the default behavior otherwise your page will refresh. Pass the submit event as an argument to your submitData()function and prevent the default behavior like so…

submitData(event) {
        event.preventDefault();
        firebase
          .database()
          .ref(`Newdata/${this.state.uid}`)
          .set({
            firstName: this.state.firstName,
            lastName: this.state.lastName,
          })

      }

Forms are old school HTML, from the days before single page applications, so when using them in a fancy new framework like react you have to specifically tell it not to automatically reload the page. It reloads by default because that is how the web used to work until single page applications came along.

Provided all code and added a console log from the database onMount to show that the data is being stored and retrieved. Copy into editor and it should work.

import React, { Component } from 'react';
const firebase = require('firebase');
const uuid = require('uuid');

const config = {
  apiKey: 'AIzaSyDf5i7ULK0JTWYM3_X3wMQPUaaLPRYExC0',
  authDomain: 'usurvey-419eb.firebaseapp.com',
  databaseURL: 'https://usurvey-419eb.firebaseio.com',
  projectId: 'usurvey-419eb',
  storageBucket: 'usurvey-419eb.appspot.com',
  messagingSenderId: '395101866940',
};
firebase.initializeApp(config);

class Usurvey extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uid: uuid.v1(),
      firstName: '',
      lastName: '',
    };
    this.submitData = this.submitData.bind(this);
    this.inputData = this.inputData.bind(this);
  }

  componentDidMount() {
    firebase
      .database()
      .ref(`Newdata/${this.state.uid}`)
      .on('value', snap => console.log('from db', snap.val()));
  }

  submitData(event) {
    event.preventDefault();
    firebase
      .database()
      .ref(`Newdata/${this.state.uid}`)
      .set({
        firstName: this.state.firstName,
        lastName: this.state.lastName,
      })
      .catch(error => console.log(error));
  }
  inputData(event) {
    const firstName = this.refs.name1.value;
    const lastName = this.refs.name2.value;
    this.setState({ firstName, lastName });
  }
  render() {
    return (
      <div>
        <form onSubmit={this.submitData}>
          <input type="text" onChange={this.inputData} ref="name1" />
          <input type="text" onChange={this.inputData} ref="name2" />
          <input type="submit" />Submit
        </form>
      </div>
    );
  }
}
export default Usurvey;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply