[英]How to fetch data from firestore in react native expo?
I have a database in firestore.我在firestore中有一个数据库。 I want to retrieve that data from firestote I don't know what is the problem, I am getting an empty array as result.
我想从 firestote 检索该数据我不知道是什么问题,结果我得到了一个空数组。
import React, { useState, useEffect } from "react"; import { StyleSheet, Text, View, TouchableOpacity } from "react-native"; import { globalStyles } from "../styles/global"; import { FontAwesome } from "@expo/vector-icons"; import ItemCat from "./menu/itemCat"; import AsyncStorage from "@react-native-async-storage/async-storage"; import firebase from "../firebase"; const category = ["Starters", "Biriyanis", "Breads", "Icecreams"]; export default function MenuBody({ navigation }) { const [toggle, setToggle] = useState("toggle-off"); const [fdata, setFdata] = useState([]); const [isLoad, setIsLoading] = useState(false); const db = firebase.firestore(); const docref = db.collection("menu"); useEffect(() => { const cat = []; console.log(docref); const fetchCat = async () => { await docref .get() .then((querySelector) => { querySelector.forEach((item) => { const data = item; cat.push(data); console.log(data); }); }) .catch((err) => { console.log(err); }); setFdata(cat); console.log(fdata); }; fetchCat(); //CALLING FUNCTION }, []);
console.lof(fdata) returns an empty array. console.lof(fdata) 返回一个空数组。 Please help me.
请帮我。
Logging cat
directly instead setting it in state first should do the trick.直接记录
cat
而不是首先将其设置为 state 应该可以解决问题。 Try refactoring the code as shown below:尝试重构代码,如下所示:
const colref = db.collection("menu");
useEffect(() => {
console.log(colref);
const fetchCat = async () => {
const querySelector = await colref.get()
const cats = querySelector.docs.map((item) => item.data())
setFdata(cats);
console.log(cats);
};
fetchCat();
}, []);
I renamed docRef
to colRef
since it's a CollectionReference .我将
docRef
重命名为colRef
因为它是一个CollectionReference 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.