Make sure to send the API call before you refresh

I am facing an issue within my app with this particular piece of code.


axios.post('url', {id:123});

window.location.href = window.location.pathname + '?lang=' + this.language;

The problem lies in the fact that the request is getting cancelled, possibly due to an immediate refresh taking place.

Here's what I attempted:

window.addEventListener('unload', (event) =>  {
   axios.post('url', {id:123});
});
window.location.href = window.location.pathname + '?lang=' + this.language;

Unfortunately, this approach did not resolve the issue and the request still gets cancelled.

Is there a solution to ensure that the API request is sent before the page refreshes? I prefer not to use setTimeout as I cannot afford to wait more than 1 second for the refresh to occur.

Answer №1

Indeed, you have the right idea. The axios.post() function operates asynchronously, meaning that the page is redirected before the post action is completed. To address this issue, consider implementing the following solution:

axios.post('/api/users/unique/username', {
        data: {
            id:456
        }
    })
    .then((response) => {
        window.location.href = window.location.pathname + '?lang=' + this.language;
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some methods for replacing the iterator or values in JavaScript / Typescript Set?

Looking to create a custom ArraySet in Typescript that handles arrays as values: export class ArraySet extends Set<any> { override add(arr: any): any { super.add(arr.toString()); } override has(arr): boolean { return super.has(arr.toStr ...

Trouble arises when attempting to append a class through ng-class upon clicking

In a specific scenario, I am trying to change the border color from black to red in a div by appending a class using ng-class when clicked. However, when clicking a button, the modal opens but the class is not being appended as expected. <div ng-class ...

Enable my textbox to interpret the html img tag

Is there a way to display emoji images instead of emoji symbols when inserting them into my textbox? For example, can I show the image representation of ':)' instead of just the symbol itself? ...

What is the best way to transfer an item to another fixed object using THREE.JS?

Having just started out, I've managed to create a scene, renderer, camera, and two objects in THREE.JS. Now I'm trying to figure out how to move one object to another object. I've tried a few things but haven't had much success. Any gui ...

Tips for Ensuring Proper Functionality of the LIKE Button on Both Client and Server Sides

On my webpage, there is a 'LIKE' Button below each post. Clicking the 'LIKE' button triggers a GET request via AJAX to a like.php page that adds a row to a MySQL database table. Once the button has been clicked by a user, it disappears. ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Only make an AJAX request for suggestions with jQuery Autocomplete if the item does not match any data from the previous request

I am currently working with jQuery Autocomplete functionality. The issue I am facing is that it triggers an AJAX request every time a key is pressed, which is not desirable. Ideally, if the data from a previous AJAX request already matches the search query ...

Experiencing pagination problems with Vue / Laravel framework

Trying to implement pagination for fetched data in a Vue project, but encountering an issue: New Question Error encountered during rendering: "TypeError: this.estates.filter is not a function" Am I overlooking something here? Pagination.vue ...

The function call datatables rows().ids() does not return a defined value

I have implemented the ID attribute for rows in my datatable: 'createdRow': function (row, data, dataIndex) { $(row).attr('id', data.json.unid); } Now, I am trying to retrieve the IDs under a button click: action: function () { ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

Best practices for managing @types/any when it is simply a placeholder for type definitions?

If I want to incorporate date-fns into my TypeScript project, typically I would obtain the typings for the library by installing its type definitions: npm install @types/date-fns --save-dev However, there are instances where only stubs are accessible. Fo ...

MVC does not have the capability to parse JSON data

Here is a snippet of my C# code: Model: namespace WebInventory.Models { [DataContract] public class PostbackList { [DataContract] public class Field { public int ID; public string Name; ...

Unscrambling jumbled JSON retrieved from axios.get

Just starting out with express and not very experienced with JS/TS. Experimenting with setting up an express server with two endpoints. The response from httpbin ( -> http://localhost:3031/simpleget) seems to be working fine. But I'm having troubl ...

Easy Steps to Showcase Blob Image in React Native

Check out my code sample: <Image source={BlobImage} style={{ height: 200, width: null, flex: 1 }} /> In this case, BlobImage represents an image stored as a blob string, like so: c916851b-3e53-432d-8d18-3de293776859?offset=0&size=371537. Updat ...

Retrieving a JSON object using a for loop

I'm working on a basic link redirector project. Currently, I have set up an Express server in the following way: const express = require('express'); const app = express() const path = require('path'); const json = require('a ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

"Learn the art of combining an ajax request with a captivating background animation at the same time

I'm currently working with the following code snippet: $('#contentSites').fadeOut(200, function() { // Animation complete $.get("my_account_content.php?q=" + content, function(data){ $("div#contentSit ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Using Vue.js 2: A guide on connecting to a component's method

Working with a VueJS (v2) component, I encountered an issue with displaying a private array of objects this.private.messagesReceived in a textarea. Despite my efforts to bind the data, Vue seems to block the serialization function from updating when the ar ...