0

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.

  • 4
    This is a common point of confusion, but async await isn't a magic bullet that turns an asynchoronous request into a synchronous one. It's just some pretty formatting on top of promises. So `login` just returns a promise because it takes some time to perform the request, and you have to handle that Promise accordingly. – Nick Dec 30 '20 at 13:14
  • 2
    Because `login` is `async`, it will always return a promise. – Patrick Roberts Dec 30 '20 at 13:14
  • I just flagged this as duplicate because the explanation in the question mentioned above is really good! Please take a look. – Nick Dec 30 '20 at 13:15
  • It's like saying "I am not sure why I have to wait for the pizza to get here when I am planning to eat it only as soon as it has arrived." – Patrick Roberts Dec 30 '20 at 13:15

0 Answers0