Using an Axios interceptor to retrieve responses directly from a Vuex store

I have implemented a login form that utilizes an axios interceptor to manage the response from the API, whether it is successful or not.

After receiving the response, it is directed to my vuex store where the user's credentials are stored.

However, when I try to log the response in my Login component, I do not see the expected fields such as data, status, and headers. Instead, I encounter something different.

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

I am wondering if there is a way to validate that the data is properly stored in the Vuex store before proceeding with the user login process?

Currently, my workaround involves utilizing a setTimeout for 3 seconds and then invoking a state getter function to retrieve the user data. While this solution works, I believe there must be a more efficient approach available.

Login.vue

onClickLogin() {
    const userToLogin = {
      username: this.loginForm.username,
      password: this.loginForm.password
    };
    const response = UsersModule.login(userToLogin);

    console.log("response", response); // displays unexpected data structure
    if (response) {
      this.$router.push("/");
    }
  }

Axios Request Class

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000
});

service.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    Message({
      message: error.message || "Error",
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

Vuex Users Login Function

  @Action({ rawError: true })
  async login(usersSubmit: UserSubmit) {
    const response: any = await loginUser(usersSubmit);
    if (typeof response !== "undefined") {
      const { accessToken, username, name } = response;

      setToken(accessToken);
      this.SET_TOKEN(accessToken);
      this.SET_USERNAME(username);
      this.SET_NAME(name);
    }
  }

API Class - Calls Axios Request via Vuex Store

export const loginUser = (data: UserSubmit) => {
  return request({
    url: "/auth/login",
    method: "post",
    data
  });
};

Answer №1

login is an asynchronous function, which means it returns a promise as described in the question.

Asynchronous control flow and promises are infectious, requiring all callers who rely on it to also use promises. It is important to note that login doesn't return anything, so it cannot resolve to a response:


  async onClickLogin() {
    const userToLogin = {
      username: this.loginForm.username,
      password: this.loginForm.password
    };

    try {
      await UsersModule.login(userToLogin);
      this.$router.push("/");
    } catch (err) {
      console.error('Login failed');
    }
  }

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 could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

I'm encountering an issue with running my VueJS unit tests - when I try to run them, I receive an error message stating that the command 'test/unit' does not

Currently, I am in the process of setting up Unit Tests with VueJS 3. After referring to Vue 3's documentation, I went ahead and installed test-utils version 2.0 Checking my package.json file, it appears like this : { "name": "testsU ...

HTML code for a grid view that allows users to expand and collapse rows in a

I'm looking for a gridview with 'n' rows, each containing 4 columns/items to be displayed. My goal is to accomplish this using an Html/Javascript/Vuejs template exclusively. The desired view should look like this: https://i.sstatic.net/kSx7 ...

What steps should I take to ensure my paths in Ionic 4 Typescript are functioning properly?

Currently, I'm in the process of transitioning my Ionic 3 application to Ionic 4 with Typescript 3.1, but I'm facing challenges with the Typescript paths. Within my tsconfig.json, I have the following setup: "paths": { "@models": [ "src/mod ...

What is the best way to incorporate a conditional type into a function's return value when the return values have a connection?

I'm trying to understand the concept behind this code snippet. There is a function: export const useProject = (id: string) => { <project fetching logic here> return { project, loading: project === undefined } } In simple term ...

Why does TypeScript struggle to locate imports within Vue class components when attempting to instantiate $refs, even though they are easily accessible when included as components?

Currently, I am developing a Progressive Web App using Vue 2.0 with the Quasar Framework, and one of the challenges I'm facing is how to close the drawer in the left slot of the layout when a menu item is clicked. Below is the script for the componen ...

Can anyone provide me with an explanation of the purpose of the "ref()" function?

I'm confused about why the "ref()" function is necessary when creating a state... The VueJS documentation provides an example like this: import { ref } from 'vue' // global state, created in module scope const globalCount = ref(1) export f ...

Using Vuejs to access and retrieve all files within a specific directory

Within a specific directory, I have the following list of files: Locale -> Test1 - abc.png -cde.png -> Test2 -egf.png I am trying to extract all the images from this directory using the code below, but it seems to be ineffective. Can ...

What is the best approach for adding TypeScript type annotations to req.body in Express without altering the original Request Type?

To specify the type of req.body as PersoneModel, I can do something like this: import { Request, Response } from 'express'; router.post('/',(req: Request<{}, any, PersoneModel>, res: Response) => { // req.body is now Person ...

Receive fresh data from the recently sorted Buefy table

I am working with a Buefy table that supports drag and drop functionality, which is documented here: The table I am using only consists of one column. After the user rearranges the rows in the desired order, they are required to click a save button. Upon ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

Updating the defaultLabel dynamically in primeNg multiselect: A step-by-step guide

In the PrimeNG multiselect component, I'm facing an issue where I can unselect items from the TypeScript file, but this change is not reflected in the input field. someComponent.html <p-multiSelect [options]="cities1" maxSelectedLabels=0 selected ...

Is it possible to utilize a library function without needing to invoke the 'this' keyword?

Is it possible to call .size(x) without calling .size() if lodash is imported in 'main.js' and used in my component? I've received advice to import lodash in my component, but I prefer a method that works across all components. Appreciate a ...

How to create a boolean observable that emits hot values with switchMap?

Looking to develop a method named isEmpty:Observable<boolean> that generates a hot Observable<boolean> by employing a switchMap. Here's what I have so far: /** * Notifies observers when the store is empty. */ protected notifyOnE ...

Dynamically populate content on render in Vue.js based on the vue.router parameters

Can anyone help me understand why I'm receiving unexpected results? I am using v2 vue.js. In my project, I have a single file component for a Vue component. The component is supposed to render data imported from "excerciseModules" in JSON format. Th ...

Issue with VueJS compilation: JSON data import causing failure

I'm attempting to bring in a static .json file within the <script> section of a .Vue file using the code snippet import Test from '@assets/test.json' From what I've gathered about webpack, this should work effortlessly. I have ev ...

NgControl was not found in the NodeInjector provider. How can I resolve this error?

https://i.sstatic.net/z4h8J.png I am encountering a problem that I have been unable to resolve despite extensive searching. Could you please provide suggestions on how to fix this issue? I have already included the following line in the application modu ...

Using Nginx with vue.js: A simple guide

I am working on developing a single page application with Vue.js, utilizing Nginx as the webserver and my own Dropwizard REST API. To make REST requests, I am using Axios. Here is how my Nginx configuration looks: server { listen 80; serv ...

Difficulty with setting up Typescript in Visual Studio Code on MacOS Catalina

I'm currently facing an issue that appears to be related to the environment. How can I resolve it? And how do I link the installed TSC to my console? Steps to Recreate: npm install -g typescript was able to successfully install or update [email ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...