简体   繁体   中英

Firebase realtime database is not getting updated

I am trying to make a simple form, and putting the user input data into firebase realtime database.

below is my code

Form.js:

import React, { useState } from "react";
import { db } from "../firebase";

const Form = () => {
    const [name, setName] = useState("");
    const [location, setLocation] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        db.collection('form').add({
            name: name,
            location: location,
        })
        .then(() => {
            console.log("Form is submitted");
        }).catch(error => {
            alert(error.message);
        });

        setName("");
        setLocation("");
    };
    return (
        <form className="form" onSubmit={handleSubmit}>
            <h1>Black eye Form</h1>
            <label>Name</label>
            <input placeholder="name" value={name} onChange={(e) => setName(e.target.value)} />
            <label>Location</label>
            <input placeholder="location" value={location} onChange={(e) => setLocation(e.target.value)} />
            <button type="submit">Submit</button>
        </form>
    );
}

export default Form;

firebase.js:

import firebase from "firebase";

var firebaseApp = firebase.initializeApp({
  apiKey: "XXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXX",
  databaseURL: "XXXXXXXXXXXXXX",
  projectId: "XXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXX",
  messagingSenderId: "XXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXX"
})
var db = firebaseApp.firestore();
export { db };

I have installed firebase in my terminal using npm install -s firebase

But my firebase realtime database is not getting updated. Also I am not getting "Form is submitted" message in my console.log when I submit the form.

EDIT: My code works when I use Cloud Firestore, but it's not working on Realtime Database. Is there something wrong with my code? or there is something which I am doing is only making it possible to update the cloud firestore and not realtime database

I have copy pasted your code to codesandbox and tried it and it worked, the screen shot of firestore:

证明

And the code sandbox console pic: 证明2

Then there is only one chance that maybe you have messed up your imports like ../firebase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM