我如何使用 React 从 firebase 9 读取数组
How can i read an array from firebase 9 using react
我想读取 firebase 中的数组
火力阵列格式:
enter image description here
并将其存储在类似于 Chart_data
我想要这种格式 enter image description here
此代码是我通常在 Firestore 中执行的代码。我不知道您在数据库中使用的是什么存储结构,但我假设您有一组用户,然后是一组图表。
如果不是,就相应地调整它。
进口:
import React, { useEffect, useState } from "react";
import { doc, getDoc } from "firebase/firestore";
import { db } from "../../../../../firebaseConfig"; // path to your firebaseConfig file
代码,粘贴到功能组件中
const [chartData, setChartData] = useState([]);
// a reference to the chart you want
const chartReference = doc(db, "dashboard_analytics", "E8V0JbotwbK9TqgtMSXF");
// used to fetch the data from your firestore database
const fetchChartData = async () => {
// attempts to fetch data for the referenced chart
const documentSnapshot = await getDoc(chartReference);
let docChartData = [];
if (docSnap.exists()) {
// the name of the field of the array
docChartData = docSnap.data().ordersGraph;
} else {
// The document doesn't exist
console.log("No such document!");
}
// stores ordersGraph array into the state variable, chartData
setChartData([...docChartData]);
};
useEffect(() => {
// calls the function on the load of the page
fetchChartData();
}, []);
然后您可以使用 chartData 状态变量访问它。
我想读取 firebase 中的数组 火力阵列格式: enter image description here
并将其存储在类似于 Chart_data 我想要这种格式 enter image description here
此代码是我通常在 Firestore 中执行的代码。我不知道您在数据库中使用的是什么存储结构,但我假设您有一组用户,然后是一组图表。
如果不是,就相应地调整它。
进口:
import React, { useEffect, useState } from "react";
import { doc, getDoc } from "firebase/firestore";
import { db } from "../../../../../firebaseConfig"; // path to your firebaseConfig file
代码,粘贴到功能组件中
const [chartData, setChartData] = useState([]);
// a reference to the chart you want
const chartReference = doc(db, "dashboard_analytics", "E8V0JbotwbK9TqgtMSXF");
// used to fetch the data from your firestore database
const fetchChartData = async () => {
// attempts to fetch data for the referenced chart
const documentSnapshot = await getDoc(chartReference);
let docChartData = [];
if (docSnap.exists()) {
// the name of the field of the array
docChartData = docSnap.data().ordersGraph;
} else {
// The document doesn't exist
console.log("No such document!");
}
// stores ordersGraph array into the state variable, chartData
setChartData([...docChartData]);
};
useEffect(() => {
// calls the function on the load of the page
fetchChartData();
}, []);
然后您可以使用 chartData 状态变量访问它。