Thursday 21 October 2021

How to save json returned from axios in a variable?

I want to save the json returned from axios into a variable. Currently I can only see it when I console.log(response.data) with the following code:

function status() {
  const url = "https://api.com";
  axios.get(url).then(function (response) {
    console.log(response.data);
  });
}
status(); // console.logs object successfully

If I just set response.data to a variable instead of logging it, it stays blank ( {} ). I want to do something like this:

let data = {};
function status() {
  const url = "https://api.com";
  axios.get(url).then(function (response) {
    data = response.data;
  });
}
status();
console.log(data); // {}
// I want to manipulate and use the properties of data in subsequent code here

How may I accomplish this please? Thank you for the help.



from How to save json returned from axios in a variable?

No comments:

Post a Comment