Gabriel Souza
Gabriel Souza

Reputation: 1015

Object is possibly 'undefined' in Vuex mutation with TypeScript

I'm learning Vue.js with Vuex and TypeScript, in the application i'm building i came across the error "Object is possibly 'undefined'" in the Vuex Store.

The error happens in the "newCard" mutation in this line:

state.board.lists.find(list => list.id === idList).cards.unshift(card)

The complete store code:

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:

// 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;
}

The response data of the board state is like this:

 {
   "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
            }
         ]
      }
   ]
}

Upvotes: 0

Views: 1842

Answers (1)

Adam
Adam

Reputation: 3518

state.board.lists.find(list => list.id === idList).cards.unshift(card)

The specific list may not be found. So you won't be able to pick cards from it.

const list = state.board.lists.find(list => list.id === idList)

if (!list) {
    // do something
    return
}

// list found so return
return list.cards.unshift(card)

Upvotes: 1

Related Questions