【问题标题】:Unsupported field value: undefined,Function addDoc() called with invalid data不支持的字段值:未定义,使用无效数据调用的函数 addDoc()
【发布时间】:2022-10-23 17:00:33
【问题描述】:

所以在这里我想将来自firebase存储的图像URL数组存储在firestore中。我收到未定义的错误,因为我的 ImageUrl 未定义。请帮我解决这个问题。图像存储在云存储中。 下面的代码显示了我的 onSubmit 函数,其中创建了表单数据的副本。我尝试过使用和不使用 '.then' 并且都给了我这个错误

const onSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    if (discountedPrice >= regularPrice) {
      setLoading(false);
      toast.error("Discounted price should be less than regular price");
    }
    console.log(formData);
    if (images.length > 6) {
      setLoading(false);
      toast.error("Max of 6 images");
    }
    let geolocation = {};
    let location;
    // if (address != null) {
    try {
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${process.env.React_App_YOUR_GOOGLE_API_KEY}`
      );
      const data = await response.json();
      console.log(data);
      geolocation.lat = data.results[0].geometry.location.lat;
      geolocation.lng = data.results[0].geometry.location.lng;
      console.log(
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      );
      console.log(geolocation.lat);
      console.log(data.status);
      location =
        data.status == "ZERO_RESULTS"
          ? undefined
          : data.results[0].formatted_address;
      if (location == undefined || location.includes("undefined")) {
        setLoading(false);
        toast.error("area does not match");
      }
    } catch (error) {
      toast.error("area does not match");
    }

    //s store image to firebase
    const storeImage = async (image) => {
      return new Promise((resolve, reject) => {
        const storage = getStorage();
        const fileName = `${auth.currentUser.uid}-${image.name}-${uuidv4()}`;

        const storageRef = ref(storage, "images/" + fileName);
        const uploadTask = uploadBytesResumable(storageRef, image);

        uploadTask.on(
          "state_changed",
          (snapshot) => {
            // Observe state change events such as progress, pause, and resume
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log("Upload is " + progress + "% done");
            switch (snapshot.state) {
              case "paused":
                console.log("Upload is paused");
                break;
              case "running":
                console.log("Upload is running");
                break;
            }
          },
          (error) => {
            // Handle unsuccessful uploads
            reject(error);
          },
          () => {
            // Handle successful uploads on complete
            // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
              resolve(downloadURL);
              console.log("File available at", downloadURL);
            });
          }
        );
      });
    };

    const imageUrls = await Promise.all(
      [...images].map((image) => {
        storeImage(image);
      })
    )
      .then(() => {
        console.log("urlready " + imageUrls);
        uploadingListings(imageUrls);
      })
      .catch((error) => {
        console.log(error);
        setLoading(false);
        toast.error("Couldn't upload image");
        return;
      });

    const uploadingListings = async (imageUrls) => {
      console.log(imageUrls);
      const formDataCopy = {
        ...formData,
        imageUrls,
        geolocation,
        timestamp: serverTimestamp(),
      };
      formDataCopy.location = address;
      delete formDataCopy.address;
      delete formDataCopy.images;
      !formDataCopy.offer && delete formDataCopy.discountedPrice;
      console.log("this is" + formDataCopy);

      const docRef = await addDoc(
        collection(db, "listings"),
        formDataCopy
setLoading(false);
        toast.success("Created a listing");
        navigate(`/category/${formDataCopy.type}/${docRef.id}`);
      });
    };

【问题讨论】:

  • 您是否尝试过console.log(formDataCopy) 并检查是否有任何字段是undefined
  • 是的,未定义的 imageUrls ......我不明白为什么它应该是

标签: reactjs google-cloud-firestore


【解决方案1】:

这就是我修复它的方法。 意识到我没有将 URL 返回给 imageUrls。 并且还发现使用 .then 和 imageUrls 并没有帮助。

const imageUrls = await Promise.all(
      [...images].map((image) => {
        return storeImage(image);
      })
    )
      // .then(() => {
      //   console.log("urlready " + imageUrls);
      //   return uploadingListings(imageUrls);
      // })
      .catch((error) => {
        console.log(error);
        setLoading(false);
        toast.error("Couldn't upload listing");
        return;
      });
      console.log("urlready " + imageUrls);
      const formDataCopy = {
        ...formData,
        imageUrls,
        geolocation,
        timestamp: serverTimestamp(),
      };
      console.log(formDataCopy);
      formDataCopy.location = address;
      delete formDataCopy.address;
      delete formDataCopy.images;
      !formDataCopy.offer && delete formDataCopy.discountedPrice;
      console.log("this is" + formDataCopy);

      const docRef = await addDoc(
        collection(db, "listings"),
        formDataCopy
      )
        console.log(docRef);
        setLoading(false);
        toast.success("Created a listing");
        navigate(`/category/${formDataCopy.type}/${docRef.id}`);
      
    
  };

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2021-12-26
    • 2021-10-05
    • 2023-01-04
    • 2019-03-08
    • 2020-06-13
    • 2021-09-26
    • 2019-12-07
    相关资源
    最近更新 更多