Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker into the markers array at the end of the chained POST and GET might be causing the issue.

Initially, this is how my code looked:

createMarker(event){
    axios.post('/marker', {
        userId: this.$store.state.auth.userId,
        marker: event.latLng
    }).then(response => {
        this.markers.push({ 'id': response.data.marker.id,
                            'lat': response.data.marker.lat,
                            'lng': response.data.marker.lng})
    }).catch((error) => console.log(error));
}

The updated version chains a POST request within the GET .then() block like this:

createMarker(event){
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key='

    axios.get(latLng)
    .then(response => {
        const name = response.data.results[0].address_components[5].long_name + ', '
                    + response.data.results[0].address_components[3].long_name
        console.log(response)
        axios.post('/marker', {
            userId: this.$store.state.auth.userId,
            marker: event.latLng,
            name: name
        }).then(response => {
            this.markers.push({ 'id': response.data.marker.id,
                                'lat': response.data.marker.lat,
                                'lng': response.data.marker.lng})
        }).catch((error) => console.log(error));
    }).catch((error) => console.log(error))
}

I need to chain the methods because I'm using Google's geocode API to retrieve the city name based on latitude and longitude, and then pass it to my POST request for saving it to my own database.

Answer №1

Absolutely correct. The end outcome is indeed a delay of two network requests. Nevertheless, your promise chain implementation could be improved for better readability and efficiency. Your current approach can lead to what is commonly referred to as callback hell. A more elegant solution would be:

createMarker(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();

    const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=';

    const userId = this.$store.state.auth.userId;

    axios.get(latLng)
        .then((response) => response.data.results[0])
        .then((x) => `${x.address_components[5].long_name},${x.address_components[3].long_name}`)
        .then((name) => axios.post('/marker', {
            name, userId
            marker: event.latLng,
        }))
        .then((response) => this.markers.push({ 
            id: response.data.marker.id,
            lat: response.data.marker.lat,
            lng: response.data.marker.lng
        }))
        .catch((error) => console.log(error));
}

By utilizing promises, you can streamline nested asynchronous calls effectively.

Answer №2

In case the id is not necessary for displaying the marker on the map, consider this approach:

Before making any GET/POST requests, add a marker with an empty id. This will help prevent any delays.

Once your POST calls are completed, update the value of id.

Make sure to review the comments in the code snippet below:

createMarker(event){
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key='

    // First, add the marker to the map
    this.markers.push({ 'id':  '',
                        'lat': lat,
                        'lng': lng})
    // Keep track of the marker's position so we can assign an `id` later
    var index = this.markers.length - 1;

    axios.get(latLng)
        .then(response => {
            const name = response.data.results[0].address_components[5].long_name + ', '
                       + response.data.results[0].address_components[3].long_name

            console.log(response)
            axios.post('/marker', {
                userId: this.$store.state.auth.userId,
                marker: event.latLng,
                name: name
            }).then(response => {
                // Update the marker's index
                this.markers[index].id = response
            }).catch((error) => console.log(error));
        }).catch((error) => console.log(error))

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

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Prevent the risk of revealing your LinkedIn API key within HTML code

For my website, I am looking to incorporate the Sign In With LinkedIn feature for user logins. The initial example snippet provided in the LinkedIn API docs is as follows: <script type="text/javascript" src="//platform.linkedin.com/in.js"> api_k ...

Leveraging the AngularJS promise/defer feature alongside the Quickblox framework, learn how to efficiently upload images and subsequently upload public URLs to a custom

I am currently developing an application that requires users to upload 5 images of themselves. Using a backend-as-a-service platform like Quickblox, I have to create and upload blob files individually. Once each image is uploaded, I receive a success call ...

What is the best way to import a YAML file into a Vue project?

As a newcomer to Vue and the world of web development, I recently embarked on building a small app. In order to store data with comments, I opted to use YAML instead of JSON. I experimented with two different YAML parsers: https://github.com/nodeca/js-ya ...

Mastering the art of capturing errors in route handlers within a Next.js project using react-query

I'm currently working on a small project where I need to verify if an email has already been registered before the user signs up, and if it is, display an error message. When a user is added successfully, everything works smoothly. However, if I try t ...

Make sure to refresh the node.js express api every minute with the latest timestamp available

I'm currently working on setting up a Node.js Express API to expose a MySQL table. Everything is working fine except for the part where I need to filter data by a current timestamp and update it every few minutes. I've tried using setInterval but ...

Quasar framework's autocomplete feature failing to display text in dropdown list

I'm currently utilizing the most recent version of quasar (0.17) and I am attempting to implement the autocomplete functionality. Although I can successfully filter the list and choose a value, the text in the autocomplete list is not being displayed: ...

Tips for closing 2 models in a React application

Currently, I am working on a project using ReactJs. One of the functionalities I am implementing is generating a user's gallery when the user clicks on their avatar. To achieve this, I am utilizing the react-grid-gallery package along with semantic ui ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Inspect each element of the array individually, and issue a warning if any two elements are identical

Trying to set up an add to cart feature and feeling a bit lost. Unsure if I should be using cookies or local storage for this task, as I'm familiar with localstorage but not sure if it's the best approach. Working with vue.js using Vuex. Ideally, ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

Troubleshooting the Issue of Angular Model Not Refreshing in Angular.js

Running into an issue with my directive where the model isn't updating as expected. Here's a snippet of my HTML code: <div class="text-area-container"> <textarea ng-model="chatText" ng-keyup="updateCount(chatText)">< ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...