I've created a function to get a user's IP address and save to a database, but instead of saving to the database, my home page is quickly and infinitely refreshing. I've tried removing watchers that may be causing this, but this did not solve the problem.
All the relevant parts that are triggering this loop:
1 - When home is mounted:
mounted() {
document.documentElement.scrollTop = 0;
IpService.getIpAddress().then((data) => {
const ip = localStorage.getItem("ip");
this.ip = data.data.ip;
if (!ip) {
VisitorsService.add(this.ip).then(()=> {
localStorage.setItem("ip",this.ip);
})
}
});
},
2 - ip service to get user's ip:
export default class ipService {
static getIpAddress() {
return axios.get("https://www.cloudflare.com/cdn-cgi/trace", {
responseType: "text",
transformResponse: data =>
Object.fromEntries(data.trim().split("\n").map(line => line.split("=")))
})
}
}
3 - This is the part where is happening the issue, if I remove this the problem stops, but it's necessary that this method works
static add(ip) {
return axios({
url: APIConstants.baseURL + "visitors/add",
method: "POST",
data: {
ip: ip
}
});
}
Conclusion: I have no idea why adding a simple axios function is causing an infinite loop on my home page. If I remove that function the issue stop. I would like to know if anyone has an idea on how can I fix this terrible loop?
Trying first stackover solution: A user suggested to use everything async it might solve the issue:
1 - mounted at home
async mounted() {
document.documentElement.scrollTop = 0;
let data = await IpService.getIpAddress();
this.ip = data.data.ip;
//The issue happens only after this add()
await VisitorsService.add(this.ip);
},
2 - ipService class
const axios = require('axios');
export default class ipService {
static async getIpAddress() {
return await axios.get("https://www.cloudflare.com/cdn-cgi/trace", {
responseType: "text",
transformResponse: data =>
Object.fromEntries(data.trim().split("\n").map(line => line.split("=")))
})
}
}
3 - Visitor service where the is the issue:
static async add(ip) {
return axios({
url: APIConstants.baseURL + "visitors/add",
method: "POST",
data: {
ip: ip
}
});
}
New conclusion changing everything to async still keep the loop problem.