'How to wait for axios function to return value when in service class

I want to structure my application with some sort of service class, but whenever I extract my axios calls from the page, then the axios function seems to return "undefined".

My page looks like this. The signin function is called when the user hits the button. When I put the axios call in the page like this, everything works fine. The usestate is updated and displays.

export default function AccountPage() {
  const [signinResponse, setSigninResponse] = useState();

  async function signin() {
    await axios
    .get(
      `...url...`
    )
    .then((res) => {
      setSigninResponse(res)
    });
  }
...

However, when I take the axios function and move it to a service class like this

import axios from "axios";

export async function tableauSignin() {
  await axios
    .get(
      `...url...`
    )
    .then((res) => {
      console.log(res);
      return res;
    });
}

and then import and make the call like this

import { tableauSignin } from "../services/tableau-online.service";
...
export default function AccountPage() {
  const [signinResponse, setSigninResponse] = useState();

  async function signin() {
    const r = await tableauSignin();
    setSigninResponse(r);
    console.log(r);
  }
...

the log from the service class is good but the log on the account page is undefined.



Solution 1:[1]

As @RobinZigmond mentioned in comment. The following solution will work but it's a needless.

it's a needless verbose way of just doing export function tableauSignin() { return axios.get(url).then(response => response.data) }.

export async function tableauSignin() {
  return await axios.get(url).then(response => response.data)  
}

This Solution may be more useful

const getData = async () => {
    let res = await axios.get("url");
    let { data } = res.data; //or res
    return data;
};

You can also import this way

var response = await getData();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1