Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!