[英]Can't get data from React-Native-Firebase(v6) Firestore: undefined is not a function (near '...this._firestore.native.collectionGet...')
[英]Can't get data from firebase in react chart
我在我的 React 項目中使用 ApexChartJs,但是當我嘗試從我的 firebase 數據庫中獲取動態數據時,然后顯示undefined
。
這是我項目中的部分代碼:
import React, { useEffect, useState } from "react";
import Chart from "react-apexcharts";
import { auth, db } from "./firebase";
import { useCollection } from "react-firebase-hooks/firestore";
const [dataPoint, setDataPoint] = useState([]);
const query = db.collection("data");
const [snapshot, loading, error] = useCollection(query);
const [series, setSeries] = useState([]);
useEffect(() => {
setSeries([
{
name: "Desktops",
data: snapshot?.docs.map((doc) => doc.data().value),
},
]);
}, [snapshot]);
console.log(series);
firebase 中的數據如下所示:
firebase 配置文件:
import firebase from "firebase";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyC2mfjPdIdXxGgJFqqVviw32xoaEMxxxxxx",
authDomain: "chart-app-4591b.firebaseapp.com",
projectId: "chart-app-4591b",
storageBucket: "chart-app-4591b.appspot.com",
messagingSenderId: "995691438244",
appId: "1:995691438244:web:6d945f72ff51d444664631",
measurementId: "G-2B9ZFG6E33",
};
const app = firebase.initializeApp(firebaseConfig);
const db = app.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
const auth = firebase.auth;
export { db, provider, auth };
如果您的firebase應用程序設置正確且配置正確,則可能導致undefined
查詢結果的主要問題是結果仍在加載中。
為了克服這個問題,您應該在loading
屬性更改時更新您的series
state(連同查詢結果snapshot
更改):
const query = db.collection("data");
const [snapshot, loading, error] = useCollection(query);
useEffect(() => {
setSeries([
{
name: "Desktops",
data: snapshot?.docs.map((doc) => doc.data().value),
},
]);
}, [loading, snapshot]);
您還應該為 state 更新提供替代error
處理。
一個常見的錯誤來源是缺乏從配置的Firestore DB 讀取和寫入的權限,以下錯誤消息突出顯示:
FirebaseError: Missing or insufficient permissions
要允許僅測試模式的所有讀取和寫入(生產系統永遠不應該是這種情況) ,您可以為數據庫設置以下安全規則:
// Allow read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
您可以在官方文檔中閱讀有關Cloud Firestore 安全規則的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.