2

I'm trying to assign the axios response data to a variable I've defined in global scope. In console i get undefined if I try to log the variable after a value it's assigned in then() callback. How I can fix and avoid this error in future?

let eas;

const fetchData = () => {
  axios({
    method: "GET",
    baseURL: "https://example-api.com",
    responseType: "json"
  }).then( (response) => {
    eas = response.data;
  });
  console.log(eas); // this will result in undefined
}

NB: I'm inside a promise callback. I've readed the suggested question but I don't want to create a function only to assign the response value, it will be overkill for my app.

miko
  • 109
  • 2
  • 9
  • 1
    Return the Promise so you can call `.then` on it from the caller. `fetchData().then((response) => { ...` – CertainPerformance Sep 06 '20 at 06:39
  • @CertainPerformance I have other operations inside the function that are related to the `webRequest` api and I need the variable after the axios call to set the `urls` array of filters. I can't run a promise, I'm not calling any function as consequence of the `fetchData()`! – miko Sep 06 '20 at 06:42
  • Returning the Promise so you can call `.then` on it is by far the best way to do it. The only other option is to pass a callback into `fetchData` and then call it in a `.then` that `fetchData` calls, but that's a bit odd. Those are your only real options. – CertainPerformance Sep 06 '20 at 06:44
  • @CertainPerformance I've solved using async/await anyway tahnks for the tips! – miko Sep 06 '20 at 12:56

0 Answers0