I'm trying to use setInterval which should perform a fetch every 60 secs. The axios response data has a valid value but if i try to assign it to a variable, it does not work.
Am I missing something?
async function fetch_data() {
axios
.get("https://url.tld/data")
.then((res) => {
console.log(res.data); // shows data
return res.data;
})
.catch((error) => {
callback({ success: false, error: "could not fetch data" });
});
}
setInterval(async () => {
let data = null;
try {
data = await fetch_data();
console.log("Fetched data:", data); // is null
} catch (error) {
console.error("Error fetching data:", error);
}
}, 60000);
The main issue is that the fetch_data function is not properly returning the fetched data.
const axios = require('axios'); // Ensure axios is imported
async function fetch_data() {
try {
const res = await axios.get("https://url.tld/data");
console.log(res.data);
return res.data;
} catch (error) {
console.error("Error fetching data:", error);
return null;
}
}
setInterval(async () => {
try { const data = await fetch_data();
console.log("Fetched data:", data);
} catch (error) {
console.error("Error fetching data:", error);
}}, 60000);