Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda