I am trying to add a login feature to my react app and I have a function that sends a post request to the API which returns a token back. I have used async/await in the login function. Here's my code:
Login.js
import axios from "axios";
const baseUrl = "/api/login";
const login = async (user) => {
const res = await axios.post(baseUrl, user);
console.log(res.data) //here it logs the data but the return value is unresolved promise.
return res.data;
};
export { login };
The part using the functionality is:
const handleSubmit = async (e) => {
e.preventDefault();
let user = await login({
username,
password,
});
setUser(user); //Adding the user to component state.
}
I am not sure why I have to call the login function with await when I am returning the res.data only after the post request has finished:
const res = await axios.post(baseUrl, user);
Without the await, the login function just returns an unresolved promise.