【问题标题】:Can't get data from firebase in react chart无法从反应图表中的firebase获取数据
【发布时间】:2021-08-23 14:03:19
【问题描述】:

我在我的 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 };

【问题讨论】:

  • 请显示快照?.docs
  • @Viet 我从需要获取数据的 firebase 添加了一条信息。
  • 请在console.log显示
  • 是的,我在第一张图片上添加了控制台输出。
  • console.log( snapshot?.docs)

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

如果您的 firebase 应用设置良好且配置正确,则可能导致 undefined 查询结果的主要问题是结果仍在加载中。

为了克服这个问题,您应该在loading 属性更改时更新您的series 状态(连同查询结果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]);

您还应该为状态更新提供替代的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 Security Rules in the official documentation 上阅读更多内容。

【讨论】:

  • 嗨@tmarwen 感谢您的解释,我知道我的查询中的问题,但我想知道您可能会在图片上方看到关于firebase db的图片,我写了data然后分配值,然后为什么我无法获得价值。
  • 我发布的修复/更新是否导致不同的结果?您能否在主 OP 评论中添加我已经要求的 firebase 设置部分?
  • 我在主帖上添加了 firebase 设置文件。如果有任何错误,请告诉我。
  • 除非我遗漏了什么,否则配置是正确的。请您一次性登录(console.logsnapshotloadingerrorconsole.log(snapshot, loading, error)
  • 这三个?我不是只指向snapshot 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2021-10-25
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多