Initiate asynchronous function

After making my action asynchronous, I encountered a problem where the dispatch is not working as expected. Every time I dispatch the action, it seems to immediately enter the catch block with the value of false. Here is the section of code from my page where I trigger the action using the mounted hook (I also tried using created):

mounted () {
  this.$store.dispatch('productById', this.$route.params['id']).then((response) => {
    this.product = response
  })
  .catch(err => {
    console.log(err)
  })
}

Below is the code snippet for my action function:

async productById ({commit}, payload) {
  const AuthStr = await getAdminOrRespondentAuth()
  return new Promise((resolve, reject) => {
    commit(PRODUCT_BY_ID)
    axios.get(`${API_BASE}/products/${payload}`, {
      params: {
        origin: '1'
      },
      transformRequest: [function (data, headers) {
        delete headers.common.Authorization
        headers.Authorization = AuthStr
        return data
      }],
      paramsSerializer: params => parseParams(params)
    }).then(response => {
      if (response.status === 200) {
        commit(PRODUCT_BY_ID_SUCCESS, response.data)
        resolve(response.data)
      } else {
        reject(response)
      }
    })
    .catch(err => {
      if (err.response.data.idStatus === 1) {
        commit(PRODUCT_BY_ID_SUCCESS, err.response.data.data)
        reject(err)
      }
    })
  })
}

Upon entering the mounted hook in Vue, the action gets dispatched but immediately hits the catch block without executing my action. This issue only occurs when the action is set to async.

Interestingly, everything works fine when the action is synchronous. However, changing it back to sync is not an option as I require the action to be async due to the getAdminOrRespondentAuth function's dependency on an async method for user retrieval.

What am I missing here?

Answer №1

@Samurai8 was absolutely correct and I am grateful for the assistance provided. It turned out that my getAdminOrRespondentAuth function was not correctly returning a promise. Once I fixed the issue within the function, everything started working smoothly again. The problematic code snippet looked like this:

async function getAdminOrRespondentAuth () {
  let mgr = new Mgr()
  var adminToken = await mgr.getToken()
  if (adminToken !== false) {
    return 'Bearer '.concat(adminToken)
  } else {
    let usrToken = localStorage.getItem('user-token')
    return 'Bearer '.concat(usrToken)
  }
}

Now, here is the revised version of the function that now functions as intended:

async function getAdminOrRespondentAuth () {
  var adminToken = ''
  return new Promise(async (resolve, reject) => {
    let mgr = new Mgr()
    try {
      adminToken = await mgr.getToken()
    } catch (error) {
      adminToken = error
    }
    if (adminToken !== false) {
      resolve('Bearer '.concat(adminToken))
    } else {
      let usrToken = localStorage.getItem('user-token')
      if (usrToken !== null) {
        resolve('Bearer '.concat(usrToken))
      } else {
        resolve('')
      }
    }
  })
}

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

Is it possible to alter the state just by clicking on the text?

I am currently facing a challenge in creating a select option for switching between notify and not notify status while using the regular text format preferred by my customer. The default value is set to notify, and upon clicking on the text it should chang ...

Struggling to design a functional mobile keyboard

I've been working on creating a mobile keyboard, but I'm facing some issues with the JavaScript part. The problem seems to be in my code as the keyboard isn't responding when I try to type. Here's a snippet of the JavaScript I'm us ...

Is there a way to automatically close the hoverable dropdown when clicking on a different link in Bulma?

Check out this interesting SANDBOX with the issue Encountered a scenario where a hoverable dropdown remains open inside a Navbar even when navigating to a different page Tested in plain Bulma, but the problem persisted Utilizing Nuxt.js with SSR for build ...

Different ways to categorize and tally a collection of objects

I'm having trouble reshaping my data in order to create a stacked bar graph. The data from the backend is structured like this: [ {date: 'January', category: 'A'}, {date: 'January', category: 'B'}, ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

What are the steps to create fixed Angular Material Chips?

I'm currently attempting to achieve a similar look and functionality as demonstrated here: https://material.angularjs.org/1.1.9/demo/chips#static-chips where the chips are static and not selectable, clickable, or hoverable. However, I am utilizing Ang ...

Can you explain the steps to implement this feature in a modal window using jQuery?

My HTML list contains a bunch of li elements. ul li img .det li I am looking to create a modal popup that appears when I click on something. I want this modal popup to have previous and next buttons, preferably implemented using jQuery. I have alr ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Warning occurs when trying to access frame with URL in JavaScript; issue arises in poltergeist but not selenium-webdriver

I've been using Selenium-Webdriver as the javascript driver for running Cucumber tests on my Rails app and had consistent results. Recently, I decided to switch to Poltergeist to run headless. Some of my tests involve a Stripe transaction that trigge ...

Navigating to the end of a webpage using Vuetify

I am looking to create an application that consists of multiple card views and a button that scrolls the page to the bottom upon each click. While I have come across solutions using native JavaScript for scrolling, I am unsure how to implement this functi ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

Discover the steps for activating Vue devtools in production mode specifically for Chrome extensions

I am currently working on a chrome extension project and have configured it using the vue-cli webpack setup. My goal is to be able to access the vue devtools tool after running the npm run build command. I attempted to include Vue.config.devtools = true; ...

Trigger the change-event by hand

Hey there, I'm facing an issue with manually triggering a change event. Currently, I have a selectOneMenu (similar to a dropdown in JSF) with various values. When I select a value from this dropdown list, a datatable is supposed to be updated. This ...

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

Develop an Electron JS desktop application utilizing the power of Python and React JS

Looking to develop a desktop application using Electron JS and React JS for the front end. I am well-versed in Python, but most resources online suggest creating an API and running it locally, which would require users to have Python installed. However, ...

Is there a way to determine the length of the visible section of an overflowing element?

Currently, there is a table with numerous rows causing it to overflow the vertical axis of the document viewport: https://i.sstatic.net/YoqKk.png As you can observe, only a portion of the table is visible when the document loads. How can we determine the ...

The router.delete function is not working properly because of an 'UnauthorizedError: Unauthorized'. Can you explain why this is happening?

I am facing an issue with one of the routes in my Vue project. Despite having a consistent structure for all routes, one specific route keeps giving me an unauthorized error. Here are the routes in question: router.get('/:userId/reviews', checkJ ...

Using JavaScript to sort through JSON data arrays

I am dealing with a JSON data structure as shown below: var data = [ { "type": "Feature", "id": 1, "properties": { "name": "William", "categorie": 107, "laporan":"Fire", "time":1, ...

Using values from a designated line within the textarea to successfully submit a GET form

How can I extract values from a specific line in a TextArea and use them to submit a form? <!DOCTYPE html> <html> <body> <input type='button' value='submit' onclick='document.getElementById("submit-line-3") . ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...