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.
useEffect(() => { const expensesListResp = async () => { await axios. get('http://localhost:4000/app/expenseslist') . then( response => console. log(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 .
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; };
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.
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));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With