I attempted to utilize Axios in the actions of my Vuex system to retrieve data from a RestAPI and then display it in components. To test this out, I created a small app using a sample API, but encountered an error.
The API I used can be found here. It contains 5 keys: "postId", "id", "name", "email", and "body". For my app, I only needed to display the "id" information in my component. However, I kept getting an error message that said "TypeError: Cannot read property 'id' of undefined."
Here is a snippet of my Vuex code:
import { MutationTree, ActionTree, GetterTree } from "vuex";
import { RootState } from "../types";
import { Customer } from "../types/customer";
import axios from "axios";
interface State {
customer: Customer;
}
export const state = () => ({
customer: []
});
export const getters: GetterTree<State, RootState> = {
customer: (state: State) => state.customer
};
export const mutations: MutationTree<State> = {
setCustomer(state: State, customer: Customer) {
state.customer = customer;
}
};
export const actions: ActionTree<State, RootState> = {
getCustomerInfo: async ({ commit }) => {
const data = await axios.get(
"https://jsonplaceholder.typicode.com/posts/1/comments"
);
commit("setCustomer", data.data.customer);
}
};
export default {state,getters,mutations,actions}
In order to define the types for RootState and Customer, I created separate files in the types directory:
export interface RootState {}
export interface Customer {
postId?: number;
id?: number;
name?: string;
email?: string;
body?: string;
}
Lastly, here is a snippet of my Vue component:
<template>
<div>
<Counter />
<p>vuex test</p>
<p>{{ customer.id }}</p>
</div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { Customer } from '~/types/customer'
const SCustomer = namespace('customer')
@Component({})
export default class extends Vue {
@SCustomer.Action getCustomerInfo!: Function
@SCustomer.State customer!: Customer
async created() {
await this.getCustomerInfo()
}
}
</script>
If anyone could offer some advice on how to properly set the data in the mutations through actions, I would greatly appreciate it!