简体   繁体   中英

Storing the data on firebase Realtime Database does not

Note: I'm a beginner in Firebase and this question may be a duplicate.

I'm trying to store data in the Firebase Realtime database but data does not store this is a database Rule.

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

This is code:

import {ref,set, getDatabase } from 'firebase/database';
function handleAddCartItemSave(product) {
        const db = getDatabase();
        const uid = selectorLogin.uid;

        set(ref(db, '/cart'),  { 
            product, 
            uid,
        });
        console.log(uid, product);
    }

What is a mistake in the above code?

Try using this.

const db = getDatabase();
const ref = db.ref('/cart');
ref.set({
    product: product,
    uid : uid
})

Setting overrides data at that specific location, if you want to store multiple cart objects I would recommend using push here. Looks like you are using the v9 api syntax,

Based on their documentation found here:

First make sure you've properly initialized the web sdk in your project with the provided firebase credentials Read more about this here:

Then you can push/set information as follows below:

import { getDatabase, ref, push, set } from "firebase/database";

// Create a new post reference with an auto-generated id
const db = getDatabase();
const uid = selectorLogin.uid;
const cartRef = ref(db, 'cart/');
const newCartRef = push(cartRef);
set(newCartRef, {
    product, 
    uid,
});

Things to check

  • Check that the firebase app was initialized properly
  • Double check that the values you are trying to store are initialized and not undefined,
  • You should push to a new reference inside cart, although may not be what you intend. If this is not what you intend, there are still other suggestions in this answer that may assist.

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