The issue with Vuex and Typescript is that when using mutation object payloads, they are consistently undefined

Every time I run my code, the object payload I'm passing as a secondary parameter to my Vuex mutation method ends up being undefined. Both my Vuex and component files are coded in TypeScript.

When looking at my index.ts file for my Vuex store (where I follow the modular store approach), it appears like this:

import Person from '@/models/Person'
import { createStore } from 'vuex'

const userModule = {
  state: () => ({
    person: Person
  }),
  mutations: {
    setPerson (state:any, person: Person) {
      // `state`
      state.person = person 
    } 
  },
  getters: {
    getPerson (state:any) {
      return state.person
    }
  }
}

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user: userModule
  }
})

I make a commitment to the store from my Vue component's methods using this pattern:

 <script lang="ts">
 export default Vue.extend({
    methods: {
      bringPersonInfo() {
        axios
            .get("/getUserInfo", requestHeader)
            .then((personResponse: Person) => {
              //store person's information in Vue Store
              store.commit('setPerson', personResponse)
            })
      }
    }
 })
 </script>

Can you help me identify the mistake I'm making?

Answer №1

When using the axios.get().then() method, the callback function specifies a parameter of type AxiosResponse, which contains the actual response data within its data property. Here is an example of how this should be implemented:

import axios, { AxiosResponse } from 'axios'

axios.get(/*...*/)
  .then((response: AxiosResponse) => {
    const profileResponse = response.data
    store.commit('setProfile', profileResponse)
  })

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 is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

When attempting to upgrade from Angular 10 to 13, users may encounter the following error message: "TS2307: Unable to locate module 'path_to_service' or its corresponding type declarations."

I initially developed my Angular App using the paper-dashboard template with Angular version 10.0. Recently, I upgraded to Angular version 13 and switched to a different template - WrapPixel. However, I encountered an error when trying to include a servi ...

Display an error message when the button is clicked and the input field is left empty in a Vue 3 script setup

Hello, I am currently exploring Vue 3 and embarking on a new Vue 3 project venture. However, I seem to be encountering a challenge when it comes to displaying an error message if the button is clicked while the input field remains empty in my Vue 3 script ...

Adding Images Using Angular 8

I'm encountering difficulties with image upload in the file located at '../src/app/assets/'. Below is the Form I am using: <form [formGroup]="formRegister" novalidate=""> <div class="form-group"> <label for="ex ...

Mastering Dropdown Navigation and Value Setting in Angular

I am facing a challenge with two components named ComponentA and ComponentB. In ComponentB, there is a link that, when clicked, should navigate to ComponentA and send specific data to it. This data needs to be displayed in the dropdown options of Component ...

Dismiss the validator upon completion of submission

Two textboxes were created, one for the title and another for the name. Validations have been implemented to only submit information if both textboxes are filled. The issue arises when attempting to clear the variable values after submission, triggering ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Unit Test: What is the proper way to activate a trigger event on an input that triggers a function in Vuex?

I am working with a bootstrap vue component: <b-form-input v-model="currentUser.name" placeholder="Name *" name="name" @input="checkSubmitStatus()" ></b-form-input> In the methods sec ...

The error message "Jest Nuxt Cannot read property 'child' of undefined" indicates a problem where a property

Having trouble running Jest tests for Nuxt/Vue components. I've connected everything needed for testing, fixed issues with jsdom and babel, but can't figure out the Vue component problem. The error message is: TypeError: Cannot read property ...

Lumen - Issue with CORS: request successfully completed despite missing 'allow origin' header

I am facing an issue with my Lumen-VueJs application When I make a request, the status is 200 and I receive the expected response, but the request appears to be blocked on the 'network' (see screen below): In my app, I have a CorsMiddleware con ...

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...

Configuring the default value for a selection menu in Vue3

Obtaining all available categories: const fetchCategories = async () => { let response = await axios.get(`/api/get_all_category/`) categories.value = response.data.categories } The structure of categories.value is shown here: https://i.sstatic.net ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

Redirecting users conditionally after login based on their roles in Vue-auth system

I am currently experimenting with websanova/vue-auth for my application and I am facing some challenges in achieving the following: Implementing redirection after login based on the user's role Granting access to certain routes depending on the user ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

The 'newPassword' must be included as a String parameter

SOLVED The issue has been resolved. It was found that the backend required data in param format, so the form sent by Vue was changed to param instead of data! I am currently working on a password change page. I encountered an error stating that there was ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

Data types for keys and values in TypeScript

interface A { a?: number }; interface B { a?: string }; function replicate< Source extends object, Destination extends { [key in keyof Source]?: (1) } >( source: Source, key: keyof Source, destination: Destination, converter: ...