Pranav M
Pranav M

Reputation: 78

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"
        );
      }
    })();
  };

Upvotes: 0

Views: 661

Answers (2)

dimaslz
dimaslz

Reputation: 515

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.

Upvotes: 2

Quentin
Quentin

Reputation: 943163

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.

Upvotes: 2

Related Questions