Mahi Parmar
Mahi Parmar

Reputation: 525

How do I add a React form data to a Firebase real-time database?

I am an new to reactjs. I am using fireadmin dynamic admin panel purchased version,in this panel i have created a page which contain a form.Now i wanted to save that form value to my firebase database.This admin panel has functionality to add data using schema file.But i wanted to add data from front end.I have followed the tutorial video tutorial. If u have any guidance please let me know.it also gives me error firebase is not function.

my function

 import Config from   '../config/app';    
 import DbConfig from   '../config/database';
    handleChange(event) {
        this.setState({value: event.target.value});
    }


addMessage(e){
    e.preventDefault(); // <- prevent form submit from reloading the page
    /* Send the message to Firebase */
   DbConfig.database().ref('billing').push(this.inputEl.value,this.inputEm.value);

    this.inputEl.value = ''; // <- clear the input
    this.inputEm.value = ''; 
  }

          render() {
        return (
                <div className="content">
                <NavBar></NavBar>
          <div className="row">
            <div className="col-md-10">
                <div className="card">
                    <form onSubmit={this.addMessage.bind(this)}>
      <input type="text" ref={ el => this.inputEl = el }/>
      <input type="text" ref={ em => this.inputEm = em }/>
      <input type="submit"/>

    </form>
            </div>

          </div>
                </div>
        )
      }

database.js

 import * as firebase from 'firebase';
require("firebase/firestore");
import Config from './app';

var FbApp = firebase.initializeApp(Config.firebaseConfig);
module.exports = FbApp; //this doesnt have to be database only

app.js

  //FireBase
     exports.firebaseConfig = {
         apiKey: "AIzaSyDsPufr5Dhusqal0bB8VDD9N6yv9u0Lo1E",
         authDomain: "tester-8e38d.firebaseapp.com",
         databaseURL: "https://tester-8e38d.firebaseio.com",
         projectId: "tester-8e38d",
         storageBucket: "tester-8e38d.appspot.com",
         messagingSenderId: "490493205074"
     };

Upvotes: 4

Views: 12126

Answers (4)

Ayza Hamid
Ayza Hamid

Reputation: 71

First of all add firebase package from npm.

-> config/fire contains firebase information

Student.js

import 'bootstrap/dist/css/bootstrap.min.css';
import React, { Component } from 'react';
import './App.css';
import fire from './config/fire';
import Home from './Home';
class Student extends Component {
constructor() {
super()
this.state = {
    email: '',
    password: ''}
this.Change = this.Change.bind(this);
this.press = this.press.bind(this);
}
Change(e) {
    this.setState({
        [e.target.name]: e.target.type === 'number' ? parseInt(e.target.value) : e.target.value,
    });
}
press(e) {
    e.preventDefault();
    var nmbr = this.state.userId + 1
    if (e.target.innerText === "Signin") {
        this.setState({
            redirect: true,
            userId: nmbr
        }, () => {
            fire.database().ref("Students/").child("userdata").set({
                password: this.state.password,
                email: this.state.email,
            }).then((data) => {
                //success callback
                console.log('data ', data)
            }).catch((error) => {
                //error callback
                console.log('error ', error)
            })
        })
    }
}
render() {
return (
    <form className="center
    <h1 style={{ textAlign: 'center' }}>{this.props.value} </h1>
        <div className="col-md-4 center boundary">
                <div className="form-row center">
                    <div className="form-group col-md-11 center Text-center" >
                        <label htmlFor="inputEmail">Your Email</label>
                        <input type="email" onChange={this.Change} className="form-control" id="inputEmail" name="email" placeholder="Email" />
                    </div>
                </div>
                <div className="form-row center">
                    <div className="form-group col-md-11 center Text-center">
                        <label htmlFor="inputPassword">Set Password</label>
                        <input type="password" onChange={this.Change} className="form-control" id="inputPassword" name="password" placeholder="Password" />
                    </div>
                </div>
                <div className="form-row center">
                    <div className="form-group col-md-5 center text-center">
                        <button type="submit" onClick={this.press} className="btn btn-primary ">Signin</button>
                    </div>
                </div>
            </div>
        </form>
    );
  }
}
export default Student;

Upvotes: 1

Mahi Parmar
Mahi Parmar

Reputation: 525

Fianlly i have found my solution and here is what i have done to resolved my issue. Thanks @Josh Pittman for your guidance without it i cant not make it out works.

  import Config from   '../config/app';
    import DbConfig from   '../config/database';  
     addMessage(e){
            e.preventDefault(); // <- prevent form submit from reloading the page
            /* Send the message to Firebase */
            var userInfo = {
                billing_name : this.pnm.value,
                billing_flat : this.fno.value,
              }; //user info
            DbConfig.database().ref('billing').push(userInfo);

            this.pnm.value = ''; // <- clear the input
            this.fno.value = ''; 
          }
     render() {
        return (
                <div className="content">
                <NavBar></NavBar>
          <div className="row">
            <div className="col-md-12">
                <form onSubmit={this.addMessage.bind(this)}>
              <input type="text" ref={ el => this.inputEl = el }/>
              <input type="text" ref={ em => this.inputEm = em }/>
              <input type="submit"/>

            </form>
            </div>

          </div>
    </div>
        )
      }

Upvotes: 2

Josh Pittman
Josh Pittman

Reputation: 7324

If the this.handleChange in your .form-control the input element is saving the input value to the state, then you need to save that state value to firebase on form submit. Use react dev tools to make sure what you want is being saved to state, or show us the handleChange method so we can see.

At the moment you are pulling from firebase on in your handleAdd method. Remove all the this.rootRef.once... code, that's for reading data. You want to write data.

Instead, first make sure you have your database function handy. It is unclear from your response above where you have written let database = firebase.database();. If it's in the same file as the code you have shown then replace this.rootRef.push(NewTodo) with database.ref().push(NewTodo) in your handleAdd method.

If let database = firebase.database(); is not in the same file then you will need to export the database reference you just created and then import it at the top of the file you want to use it in. If the error you are getting is database is not a function then this is most likely the problem. Where are you setting up the SDK? If you explain this it will be easier to help you. I explain the basic of setup react and firebase in a post here https://joshpitzalis.svbtle.com/setup, it's for firestore database but its basically the same approach for the real-time database.

Another point of confusion is where the text parameter in handleAdd(text) is coming from. It is also unclear where you're using the handleAdd method. You seem to be using this.handleSubmitFirebase on form submit and this.handleChange on input change but you haven't shown us the code for either method so it's really confusing. Make sure the handleAdd(text) is connected to the UI somehow, I'd use it on form submit.

Upvotes: 1

Muneeb
Muneeb

Reputation: 1549

First of all add firebase package from npm.

npm install firebase --save

Then, import firebase instance

import * as firebase from 'firebase';

let database = firebase.database();
database().ref('/users').once('value')
 .then(function (snapshot) {
  console.log(snapshot.val())
});

Upvotes: 0

Related Questions