Yash Choksi
Yash Choksi

Reputation: 513

Save React form values to firebase real time database

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;

Upvotes: 3

Views: 3172

Answers (1)

Josh Pittman
Josh Pittman

Reputation: 7324

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;

Upvotes: 1

Related Questions