Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
kylel9506 Avatar asked Jul 31 '20 08:07

kylel9506


People also ask

How do I assign a response to a variable in Axios?

useEffect(() => { const expensesListResp = async () => { await axios. get('http://localhost:4000/app/expenseslist') . then( response => console. log(response.

Does Axios convert JSON response?

Axios automatically converts the data to JSON, so you don't have to: // axios const url = 'https://jsonplaceholder.typicode.com/posts' const data = { a: 10, b: 20, }; axios .

How do I return data from Axios?

To return data from axios API with JavaScript, we can use the return statement. const axiosTest = async () => { const response = await axios. get(url); return response. data; };

Does Axios convert JSON to object?

post() function, Axios will automatically serialize the object to JSON for you. Axios will also set the Content-Type header to 'application/json' , so web frameworks like Express can automatically parse it.


1 Answers

The function axios.get(url) returns a Promise. You can use async/await like so.

 async function status() {
  const url = "https://api.com";
  let response = await axios.get(url);
  return response.data;
}

status().then((data) => console.log(data));

like image 197
Rahul Bhobe Avatar answered Nov 14 '22 20:11

Rahul Bhobe