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"
);
}
})();
};
CodePudding user response:
dbConnect
is marked as async
so it returns a promise. It asynchronously calls fetch
(without await
ing 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.
CodePudding user response:
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;
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) => data.json());
} catch(error) {
console.log("setted Error");
setSignupError(error);
return null;
}
};
I think you just forget the return.