Unable to retrieve store states in Vuex using getters through the promise chain

My approach to verifying whether the channel route input requires a PIN code involves using router.beforeEach as outlined below:

router.beforeEach((to, from, next) => {  
  if(to.path == '/') {
    next();
  }else {                
    store.dispatch('checkChannelhasPin', to.params.id).then(()=>{
    console.log(store.getters);
    console.log(store.getters.ispin);
    setTimeout(() => {
      console.log(store.getters.ispin);
     }, 500);
   }) 
  }
}

Upon console.log evaluation, three results are observed:

https://i.sstatic.net/flARp.png

The challenge faced is the inability to retrieve stateispin post 'checkChannelhasPin' verification.

The action plan is depicted as follows:

import axios from 'axios';
import setChannelAuthToken from '../../utils/setChannelAuthToken';
import {
  CHECK_CHANNEL_HASPIN
} from '../typeName';

const state = {
  ispin: true,      
}

const getters = {  
  ispin: (state) => state.ispin
};

const actions = {      
  async checkChannelhasPin({commit}, params) {    
    axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    ).then((response) => {      
      let payload = response.data.ispin;
      commit(CHECK_CHANNEL_HASPIN, payload); 
    }).catch( (error) => {
      console.log(error);
    });
  }
}


const mutations = {
  CHECK_CHANNEL_HASPIN: (state, payload) => (state.ispin = payload)
};

export default {
  state,
  getters,
  actions,
  mutations
};

Your suggestions and advice would be highly appreciated. Many thanks in advance.

Answer №1

To properly handle promises in your action, make sure to return the promise like this:

checkChannelhasPin({commit}, params) {    
  return axios.post(
    window.home+'/json/channel/checkAuth',
    {
      channel_id:params
    }
  ).then((response) => {      
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  }).catch( (error) => {
    console.log(error);
  });
}

If you prefer using async/await syntax, you can rewrite the function as follows:

async checkChannelhasPin({commit}, params) {
  try {
    const response = await axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    )
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  } catch(error) {
    console.log(error);
  }
}

Remember, when using .then, you need to explicitly return the promise. With async/await, this is not necessary. The issue in your code was that you were using both the async keyword and .then instead of await.

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

Leverage JavaScript Object Properties within Angular 5 Components

Here's a question I have on using ngx-charts in Angular 5. I am experimenting with ngx-charts to create a chart within my Angular 5 project. The code snippet for my component is shown below: import { Component, OnInit } from '@angular/core&ap ...

Having trouble with this.props.history.push() in ReactJS?

Experimenting with ReactJS fetch() scenarios. I've encountered an issue where this.props.history.push() isn't working as expected - it's not throwing an error, but the redirection isn't happening. I tried looking for solutions on StackO ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...

Error in material mapping: glDrawElements is trying to access vertices that are out of range in attribute 2

I have developed an algorithm that allows users to input data or a function and then generates a graphical representation of the function. It essentially creates a surface map, similar to the one you can see here. The graphing functionality is working well ...

unable to establish connection due to port error in node.js

While executing node app.js I encountered the following error message info - socket.io started warn - error raised: Error: listen EACCES This snippet shows all the JavaScript code within the application. After running sudo supervisor app.js T ...

Encountering the 502 Bad Gateway Error while utilizing jQuery Ajax POST in conjunction with PHP

My goal is to transfer data to a database using the method outlined below: <script> function add_new_activity(id) { var act_type = $("#add_new_activity #act_type").val(); var act_muscles = $("#add_new_activity #multi").val(); var act_l ...

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

JavaScript HTML Object Manipulation and Templating System

I am searching for a JavaScript library that is capable of performing the following: var items = [1, 2]; var html = div( ul({ id: "some-id", class: "some-class" })(items.each(function(item) { return li(item); })); html == ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Click to deactivate an element in an array using JavaScript

I am working on displaying an array from JavaScript in my HTML code. Here is the HTML code snippet: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <div id ="containe ...

Storing ajax data into a variable seems to be a challenge for me

I am facing an issue with my ajax call where I am receiving the data correctly, but I am unable to assign it to a local variable named item_price. The data that I am receiving can either be 100.00 or 115.25. Below is the snippet of my ajax code: $.ajax({ ...

In Express.js, the value of req.body.data is not defined

Recently, I've been delving into nodejs and express js. My aim is to send a json object to my nodejs application using postman. Below is the code snippet from my app: var express = require("express"); var bodyParser = require('body-parser') ...

Utilizing JavaScript to dynamically update the user interface after submitting a form using jQuery

I am working on implementing an Input element that triggers a form submission: <input type="submit" value="Download" id="downloadButton" class="btn-download" /> The specific requirement is for the button to first execute a javascript function and t ...

Having trouble getting an Angular directive to bind a click event to an external element?

I've been working on creating a unique custom event for toggling with Angular. The directive I'm using is called toggleable. It may sound simple at first, but the tricky part is that I want to be able to use any button or link on the page for to ...

Encountering an undefined value from state when implementing useEffect and useState

One issue I am facing is that the state of my projects sometimes returns as undefined. It's puzzling to me why this happens. In the useEffect hook, I have a function that fetches project data from an API call to the backend server. This should return ...

Is there a way for me to determine the size of this JSON structure?

Can anyone help me figure out the length of this JSON object? I need to know how many data are in it. var ddData = [{ "01":"United States", "02":"United Kingdom", "03":"Aruba", "04":"United Kingdom", ...

The assurance of quick delivery isn't effective

I am a beginner when it comes to working with promises and I'm struggling to implement them in my code successfully. Currently, I have a NodeJS server set up using the Express library along with express-promise. var express = require('express&a ...