Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

628
Visualizações
FirebaseError: Function addDoc() called with invalid data. Unsupported field value: undefined

so here I want to store the image URL from the firebase storage in firestore. I am getting an error of undefined as my setImgUrl is undefined. please help me to solve this.

import React, { useState } from "react";
import "../mainTab.css";
import "./addScreen.css";

import firebase, { storage } from "../firebase";


const AddScreen = () => {
  const db = firebase.firestore();
  const [cat, setCat] = useState();
  const [course, setCourse] = useState();
  const [name, setName] = useState();
  const [price, setPrice] = useState();
  const [descrip, setDescrip] = useState();
  const [image, setImage] = useState();
  const [imgURL, setImgURL] = useState();

  const onSubmitHandler = (event) => {
    event.preventDefault();

    const ref = storage.ref(`/images/${image.name}`);
    const uploadTask = ref.put(image);
    uploadTask.on("state_changed", console.log, console.error, () => {
      ref.getDownloadURL().then((url) => {
        setImage(null);
        setImgURL(url);
        console.log(imgURL);
      });
    });

    const data = {
      name: name,
      price: price,
      cat: cat,
      course: course,
      decription: descrip,
      image: imgURL,
    };

    db.collection("menu")
      .doc(course.toString())
      .collection(name.toString())
      .add(data)
      .then(() => alert("menu item is posted"))
      .catch((error) => alert("error: " + error));

    setName("");
    setPrice("");
    setCat("");
    setCourse("");
    setImage("");
    setDescrip("");
  };

I need the img URL in the setImg hook. so is there any way after completing the upload I should call the database writing function(I tries with a flag(false) hook which didn't help? by the image get uploaded perfectly fine into the firebase storage

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

try putting this part inside a function and then call that function inside 'then' say for example

    const putUrl = ()=>{
    db.collection("menu")
      .doc(course.toString())
      .collection(name.toString())
      .add(data)
      .then(() => alert("menu item is posted"))
      .catch((error) => alert("error: " + error));

    setName("");
    setPrice("");
    setCat("");
    setCourse("");
    setImage("");
    setDescrip("");
  }

and now call putUrl in 'then()' by this way this part of code will execute only after 'imgUrl' is fetched. You got an error because getting 'imgUrl' and adding data are both asynchronous and will get execute before 'imgUrl' is fetched

about 4 years ago · Juan Pablo Isaza Relatório

0

Any code that needs the download URL from Firebase, needs to be inside the then callback, be called from there, or synchronized to run once imgURL is set in some other way.

The simplest way to fix your code, is to move the code that writes to Firestore into the then block like this:

const ref = storage.ref(`/images/${image.name}`);
const uploadTask = ref.put(image);
uploadTask.on("state_changed", console.log, console.error, () => {
  ref.getDownloadURL().then((url) => {
    setImage(null);
    setImgURL(url);
    console.log(imgURL);

    const data = {
      name: name,
      price: price,
      cat: cat,
      course: course,
      decription: descrip,
      image: url, // 👈 Use url here, as imgURL won't be set yet
    };

    db.collection("menu")
      .doc(course.toString())
      .collection(name.toString())
      .add(data)
      .then(() => alert("menu item is posted"))
      .catch((error) => alert("error: " + error));
  });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda