A Vuex action that produces a promise never fulfills or rejects

I am currently enhancing my API service within my VueJS application by utilizing Vuex. As part of this process, I am restructuring certain aspects to streamline error handling and cleanup procedures. However, I am encountering difficulty in correctly chaining Promises across my function calls.

At the fundamental level, there is a BaseService class responsible for making API requests using AXIOS (only partial code shown):

export abstract class BaseService {
  protected readonly API: AxiosInstance; // Initialization details omitted

  protected deleteItem(url: string): Promise<any> {
    return new Promise((resolve, reject) => {
      this.API.delete(url)
        .then((response: any) => {
          resolve(response);
        })
        .catch((error: any) => {
          this.handleError(error); // Error logging function
          reject(error);
        });
    });
  }
}

Above this, there exists a layer that manages various features of the API by constructing request URLs and handling data:

class CompanyService extends BaseService {
  private constructor() {
    super();
  }

  public delete(id: number): Promise<any> {
    return this.deleteItem(`${this.baseUrl}/api/companies/${id}`);
  }
}

Furthermore, in my Vuex action, I invoke the companyService delete function:

const action = {
  COMPANY_DELETE(context: any, id: number) {
    return new Promise((resolve, reject) => {
      companyService // Instance of CompanyService
        .delete(id)
        .then((response: any) => {
          console.log(response); // Logs successfully
          resolve(response);
        })
        .catch((error: any) => {
          console.log(error); // Logs successfully
          reject(error);
        });
    });
  }
};

While the two console logs indicate success, I encounter an issue when reaching the component that triggers this action:

this.$store
  .dispatch("company/COMPANY_DELETE", company.id) // Namespaced
  .then((response: any) => {
    console.log(response); // Does not execute
  })
  .catch((error: any) => {
    console.log(error); // Does not execute
  });

Unexpectedly, these specific console logs remain uncalled. What could be causing this problem?

Answer №1

Here is a simple example showcasing how to use axios for an action without wrapping it in an extra promise...

const store = new Vuex.Store({
state: {
  followers: 0
  },
  mutations: {
  updateFollowers(state, followers){
    state.followers = followers;
    }
  },
  actions: {
    getFollowers({commit}) {
        return axios.get('https://api.github.com/users/octocat').then( (response) => {
        commit("updateFollowers", response.data.followers);
          return "success!!!";
        });
    }
  }
})

Vue.component('followers', {
  template: '<div>Followers: {{ computedFollowers }}</div>',
  created () {
    this.$store.dispatch('getFollowers').then( (result) => {
    console.log(result);
    });
  },
  computed: {
  computedFollowers() {
    return store.state.followers;
    }
  }
});

const app = new Vue({
store,
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <followers></followers>
</div>

Answer №2

After following the suggestion from Void Ray to remove the extra Promise, I found success. However, in my specific scenario, error propagation was also necessary. The code snippet below reflects the adjustments I made to achieve this.

const action = {
  COMPANY_DELETE(context: any, id: number) {
    return companyService // Instance of CompanyService
      .delete(id)
      .then((response: any) => {
        console.log(response);
      })
      .catch((error: any) => {
        console.log(error);
        throw error; // Necessary for error propagation to continue
      });
  },
};

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

Guide to shuffling an array with a simple click of a button

To simplify, I have an array that I would like to randomize by clicking a button. Once randomized, I want to display the first result from the array with another button. The array is currently randomized when opened in Chrome, and checking the results in t ...

What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below: if (firebase.apps.length) { firebase.app() } else { firebase.initializeApp(config) } export const Firestore = firebase.firestore() export const Auth = firebase.auth() ...

A guide to configuring a non-linear step in the yAxis of Highcharts

I am looking to display a chart with the following scale: Higher (increase by one tick from five to maximum) 5 4 3 2 1 0 Lower (decrease by one tick from minimum to 0) I attempted to use min/max or floor/ceiling, but it did not work yAxis: { floor: 0 ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Displaying an HTML/CSS image layered on top of another image with a fixed navigation bar

I've run into an issue with my webpage layout. I have a fixed navigation bar and an image displayed, but now I want to add another image on top of the existing one. However, when I use "position: relative" and position:absolute", the two images end up ...

Filtering data with React's multiselect checkboxes

I have created an amazing app that fetches a list of todos from this incredible source To enhance user experience, I developed a special CheckBoxDropDown component for selecting todo IDs Within the CheckBoxDropDown.js component, I am passing the onChange ...

Retrieving geographical data in GeoJSON format using AJAX request and displaying it on a Leaflet

I'm completely new to Leaflet and I'm struggling with how to integrate markers from a MySQL database onto a Leaflet map. Can anyone guide me on how to accomplish this using PHP and AJAX? .....{"type":"FeatureCollection","features":[{"geometry":{ ...

Why does the parent URL become the origin for an AJAX request coming from an iframe?

I am facing an issue with a website where I need to load an iframe from a different subdomain. The main website is hosted on portal.domain.com, and the iframe is on iframe.domain.com. To make requests to iframe.domain.com from portal.domain.com, I decided ...

Jest ran into a surprising token related to NUXT typescript

After spending two days searching and trying various solutions without success, I am reaching out for help. Can anyone provide a clue? Below are the configuration files I am using. Any assistance would be greatly appreciated. jest.config.js .babelrc .babe ...

Is there a solution to the JSON cross-domain issue other than parsing it from an iframe?

It feels like I'm guessing blindly here. I've been trying various methods to make a cross domain request for json data, but the cross domain policy keeps blocking me. Is there a way I can achieve this by parsing the data within a hidden iframe u ...

Strategies for detecting and handling blank data in JSON parsing with JavaScript

Here is a function that retrieves details: function GetSomeDetails(Param) { Json_Parameters = JSON.stringify(Param); $.ajax({ type: "POST", url: "MainPage.aspx/MyMethod", data: J ...

Exploring Nested JSON Objects with React and Axios

I am exploring the CryptoCompare API to retrieve cryptocurrency data. As a beginner with React, I have successfully used Axios for AJAX requests. However, I am facing challenges in accessing specific JSON elements. To view the JSON data structure, you can ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Javascript issue with if statement not functioning properly

If you go to the website here and attempt to click on the voting arrows, you'll encounter the issue I'm facing. Contrasting this with the homepage where clicking on the logo allows you to vote. The arrows change their appearance based on the vote ...

Associate the callback function with a directive that does not have an isolated scope

Ensuring the correct context when binding a callback function to a directive is crucial. When working with an isolated scope, this task is easily accomplished. <bar-foo callback="mycontroller.callback()"></bar-foo> The directive code: ... ...

The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backe ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Create your own custom block on the frontend product page

I am trying to create a custom block on the Product Page of my Magento store. I attempted it like this: Magento- How can i add a new custom block in product details page using module Unfortunately, it did not work as expected. Did I make any mistakes he ...

How to remove decimal points from the x-axis in jqPlot

Is there a way to show only whole numbers on the x-axis in jqPlot? At the moment, it shows: 0.5, 1, 1.5, 2, 2.5, etc. I'm looking for a method to make it display integers exclusively in the x-axis labels. ...

Full-screen modal fade not functioning properly

I am trying to implement multiple fullscreen modals on a single page, but I am facing an issue where they slide in and out at an angle instead of just fading in and out. I have been unable to achieve the desired effect of a simple fade transition. If you ...