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

149
Visualizações
Javascript fetching data and parse them on a Variable

I've been searching for a solution for my Problem, it seems actually pretty easy but it doesn't work :(. The problem is the following: I fetch data from my backend which is localhost/users. I get the data and i can console.log them. But it seems impossible for me to write it on a variable and export it. Here is my Code:

import axios from "axios";


function init() {
    let obj;
    axios('/users')
    .then(response => {
        obj = (response.data)
        console.log(obj)
        return obj
    })
    .catch(error => {
        console.log("error fetching")
        return null
    })
    
}

let obj = init()


export default obj

If i try to console.log the exported variable it just writes undefined, i guess it skips the response section. The returned Variable is undefined too

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You just need to add return keyword before axios function

import axios from "axios";


function init() {
 let obj;
 return axios('/users')
 .then(response => {
     obj = (response.data)
     console.log(obj)
     return obj
 })
 .catch(error => {
     console.log("error fetching")
     return null
 })
 
}

let obj = init()


export default obj
 ```
about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot return the value from the inner function.

To do that you can use Promises or Callback or simply React setState if you want to but it inside the component.

Using Promises:

import axios from "axios";


function init() {
    return new Promise((resolve, reject) => {
     axios('/users')
      .then(response => {
        obj = (response.data)
        resolve(obj);
      })
      .catch(error => {
        reject(error);
      })
   });
}

// To log or get the values 
init().then(obj => {
  console.log(obj);
}).catch(error => console.log(error));


export default obj

Using Callbacks

import axios from "axios";


function init(successCallback, errorCallback) {
     axios('/users')
      .then(response => {
        obj = (response.data)
        successCallback(obj);
      })
      .catch(error => {
        errorCallback(error);
      })
}

// To log or get the values 
init(obj => {
  console.log(obj);
}, error => {
  console.log(error);
});


export default obj
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