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

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

What causes the element to remain visible despite the changes made to the v-show attribute?

<!DOCTYPE html> <html> <head> <title>test</title> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <p v-show="show&qu ...

Creating a Vue JS project that utilizes both HTTP and HTTPS URLs for improved security

I'm currently utilizing Vue JS with the webpack template and dev mode. I have a question regarding how to configure my server to allow for both HTTPS and HTTP protocols simultaneously. I understand that enabling HTTPS can be done by simply adding "ht ...

Learn how to utilize a Library such as 'ngx-doc-viewer2' to preview *.docx and *.xlsx files within the application

After 3 days of searching, I finally found a solution to display my *.docx and *.xlxs files in my angular application. The API returns the files as blobs, so my task was to use that blob to show the file rather than just downloading it using window.open(bl ...

Discover the Vue Jest Framework: Invalid lines are highlighted to ensure thorough test coverage

I am experiencing a problem with my unit test cases in Vue.js when using the Jest framework. Even though my file has 31 lines of code, it is showing that lines 39 and 40 are uncovered. Could this be related to configuration settings? https://i.stack.imgur ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

How can I modify the icon once the accordion summary is expanded?

How can I switch the icon based on whether the accordion is expanded or not? I noticed that on the material ui page there is a CSS class called .Mui-expanded which can detect whether expanded={true} or false. But, how do I utilize this to change the ...

The file isn't located in 'rootDir', even though all the details seem to be accurate

I'm currently troubleshooting an issue with one package in my nx monorepo that is causing the error code "TS6059". Interestingly, all other packages are functioning correctly in previous builds. After reviewing my index.ts files, it appears that all ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

Interacting with iView UI dropdown menu items

I'm attempting to create a click event in iView ui. Here's my code: <DropdownMenu slot="list"> <DropdownItem @on-click="markAsRead">Mark as read</DropdownItem> </DropdownMenu> The function markAsRead isn't exec ...

Utilizing ESlint: A guide to effectively implementing the globally installed eslint-plugin-vue

For my workflow with Docker, I want to use the linter elint-plugin-vue as a global installation since there may not always be a node_modules folder in my repositories. I previously installed the linter using: sudo npm install -g eslint eslint-plugin-vue ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Receiving a Typescript error stating "Property '0' does not exist on type X" when incorporating auto-generated GraphQL code into the project

I'm struggling to comprehend how to rectify this typographical error. Here's the snippet of code causing me trouble: <script lang="ts"> import type { PlayerListQuery } from "queries"; export let player: PlayerListQ ...

Differences between Template Rendering and Render Function h() in Vue 3

How do you feel about the concept of template rendering in Vue 3 (or within the composition-api), specifically in terms of speed and efficiency? When building a website using simple components like ui-box or ui-button, we typically utilize functional comp ...

Save JSON Tree data in the Database

Given a tree structure JSON, I am tasked with creating an API to insert all the data into a database at once. The organization entities can have multiple parents and children relationships. An example of the JSON data: { "org_name": "orga ...

Begin by initializing a variable within the `mounted` lifecycle hook and then pass it back to

Experimenting with the new composition api. Check out the composable function useProduct.js below: export default function useProduct() { const product = reactive({}); async function getProduct(id) { try{ const response = await { ...