异步功能不返回数据库查询数据

时间:2020-11-06 15:42:57

标签: javascript reactjs firebase google-cloud-firestore

我正在查询Firebase以获取具有以下属性的特定文档:

name: 'Bob',
price: '12',
description: 'My favorite food is ice cream',
quantity: '5',

然后,我想将状态变量namepricedescriptionquantity设置为每个各自的属性值。

但是,当我运行useEffect时,这些值未设置为变量-我的控制台日志为每个变量打印undefined

我认为我的异步功能可能有问题。有什么想法吗?

useEffect(() => {
    if (user) {
      // grab document id from URL
      const params = new URLSearchParams(window.location.search);
      const pid = params.get("pid");
      setPidString(pid);
      console.log(pid);

      // query firebase db
      const docRef = db
        .collection("users")
        .doc(user?.uid)
        .collection("products")
        .doc(`${pid}`);

      //query for specific document
      docRef
        .get()
        .then(function (doc) {
          if (doc.exists) {
            async function fetchProductData() {
              const productData = await doc.data();
              console.log(productData);

              setName(doc.data().name);
              setPrice(doc.data().price);
              setDescription(doc.data().description);
              setQuantity(doc.data().quantity);
              setDownloaded(true);
              console.log("MY NAME", name);
              console.log("MY DESCRIPTION", description);
              console.log("MY PRICE", price);
              console.log("MY QUANTITY", quantity);
            }
            fetchProductData();
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function (error) {
          console.log("Error getting product data:", error);
        });
    } else {
      setProducts("");
    }
  }, [user]);

2 个答案:

答案 0 :(得分:0)

此操作count = length每次应该为library(dplyr) data <- starwars dimensionsVec <- c("skin_color", "eye_color") measuresVec <- c("height", "mass") functions <- c(count = "length", mean = "mean", sum = "sum", median = "median", max = "max", min = "min") funsList <- lapply(functions, match.fun) names(funsList) <- functions pivotData <- data %>% group_by_at(vars(dimensionsVec)) %>% summarize_at(vars(measuresVec), funsList, na.rm = TRUE) %>% collect() doc.data().someProperty的结果在productData.someProperty变量中。

然后,您还将记录未定义的变量。这些变量未声明,您也没有为其分配任何内容。

await doc.data();

您应该记录存储数据的对象的属性。

productData

记录状态也不起作用,因为没有任何东西可以保证您在调用setState后立即更新组件的状态。

答案 1 :(得分:0)

尝试一下

  async function fetchProductData() {
      const doc1 = await docRef.get();
      if(!doc1.exists){
        console.log('No such document!');

      }
      else{
          const productData =  doc.data();
          console.log(productData);
          setName(doc.data().name);
          setPrice(doc.data().price);
          setDescription(doc.data().description);
          setQuantity(doc.data().quantity);
          setDownloaded(true);
          console.log("MY NAME", name);
          console.log("MY DESCRIPTION", description);
          console.log("MY PRICE", price);
          console.log("MY QUANTITY", quantity);
        }
    }
    fetchProductData();