Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
Async-Await functionality response became undefined

Iam trying to pass URL to async function and later taking its response and trying to use its value, but here response get undefined and await not waiting until value available. what is the reason for this and how can solve this

const AuthForm = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [signupError, setSignupError] = useState("");
  const dispatch = useDispatch();
  const emailRef = useRef();
  const passwordRef = useRef();
  const switchAuthModeHandler = () => {
    setIsLogin((prevState) => !prevState);
  };
  const submitHandler = (e) => {
    e.preventDefault();
    const email = emailRef.current.value;
    const password = emailRef.current.value;
    const dbconnect = async (URL) => {
      fetch(URL, {
        method: "POST",
        body: JSON.stringify({
          email: email,
          password: password,
          returnSecureToken: false,
        }),
      })
        .then((res) => {
          if (res.ok) return res;
          else throw new Error("Failed");
        })
        .catch((err) => {
          console.log("setted Error");

          setSignupError(err);
        });
    };
    (async () => {
      if (isLogin) {
        const response = await dbconnect(
          "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyDXTW7owM4V9xy6RuUz8fI4nRKPcX-a2SU"
        );
        await response.then(dispatch(sliceActions.login(response.idToken)));
      } else {
        const response = await dbconnect(
          "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDXTW7owM4V9xy6RuUz8fI4nRKPcX-a2SU"
        );
      }
    })();
  };
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

dbConnect is marked as async so it returns a promise. It asynchronously calls fetch (without awaiting it), then gets to the end of the function without hitting a return statement so it resolves the promise as undefined.

Rewrite your call to fetch to use await and try/catch instead of .then and .catch. Return the final result.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think you forgot to return a result in dbconnect method. Try with the following code:

const dbconnect = async (URL) => {
  return await fetch(URL, {
    method: "POST",
    body: JSON.stringify({
      email: email,
      password: password,
      returnSecureToken: false,
    }),
  })
  .then((res) => {
    if (res.ok) return res.json();
    else throw new Error("Failed");
  })
  .catch((err) => {
    console.log("setted Error");

    setSignupError(err);

    return null;
  });
};

And other way:

const dbconnect = async (URL) => {
  try {
    return await fetch(URL, {
      method: "POST",
      body: JSON.stringify({
        email: email,
        password: password,
        returnSecureToken: false,
      }),
    }).then((result) => result.json());
  } catch(error) {
    console.log("setted Error");

    setSignupError(error);

    return null;
  }
};

I think you just forget the return.

Also the following lines:

if (isLogin) {
  const response = await dbconnect("your-url");
  await response.then(dispatch(sliceActions.login(response.idToken)));
} else {
  const response = await dbconnect("your-url");
}

response already has the result of the request so, you do not need to use the .then to send the dispatch so, I think you can use the following code.

if (isLogin) {
  const response = await dbconnect("your-url");

  await dispatch(sliceActions.login(response.idToken));
} else {
  const response = await dbconnect("your-url");
}

I hope it helps you.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda