Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda