Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store.
The error specifically arises in the "newCard" mutation at this line of code:
state.board.lists.find(list => list.id === idList).cards.unshift(card)
Below is the complete store code for reference:
const state: BoardState = {
board: {
id: "",
name: "",
idProject: "",
closed: false,
lists: []
}
};
const getters: GetterTree<BoardState, {}> = {
getBoard: state => state.board
};
const mutations: MutationTree<BoardState> = {
setBoard: (state, board) => (state.board = board),
newList: (state, list) => state.board.lists.unshift(list),
newCard: (state, { card, idList }) =>
state.board.lists.find(list => list.id === idList).cards.unshift(card)
};
const actions: ActionTree<BoardState, {}> = {
async fetchBoard({ commit }) {
const response = await axios.post("https://app.fakejson.com/q", json);
commit("setBoard", response.data);
},
async addList({ commit }, list) {
const response = await axios.post("https://app.fakejson.com/q", {
token: "oplF0L7vj1Ial4cRqtx9DA",
data: list
});
commit("newList", response.data);
},
async addCard({ commit }, { card, idList }) {
const response = await axios.post("https://app.fakejson.com/q", {
token: "oplF0L7vj1Ial4cRqtx9DA",
data: card
});
commit("newCard", response.data, idList);
}
};
TypeScript types used in the code are as follows:
// Store
export interface BoardState {
board: Board;
}
// Models
export interface Board {
id: String;
name: String;
idProject: String;
closed: Boolean;
lists: List[];
}
export interface List {
id: String;
name: String;
idBoard: String;
closed: Boolean;
cards: Card[];
}
export interface Card {
id: String;
name: String;
idList: String;
closed: Boolean;
}
This is a sample response data structure representing the board state:
{
"id":"1",
"name":"Tasks",
"idProject":"1",
"closed":false,
"lists":[
{
"id":"1",
"name":"To Do",
"idBoard":"1",
"closed":false,
"cards":[
{
"id":"1",
"idList":"1",
"name":"Card 1",
"closed":false
},
{
"id":"2",
"idList":"1",
"name":"Card 2",
"closed":false
}
]
}
]
}