Potential 'undefined' object detected in Vuex mutation using TypeScript

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

Answer №1

state.board.lists.find(theList => theList.id === chosenId).tasks.unshift(newTask)

If the specific list cannot be located, you will not be able to add tasks to it.

const foundList = state.board.lists.find(theList => theList.id === chosenId)

if (!foundList) {
    // take necessary action
    return
}

// list is found so proceed with adding task
return foundList.tasks.unshift(newTask)

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

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

Bidirectional data connection in a Meteor application

I've developed a form-based application and I would like to allow users to fill out the form partially and return to it at a later time if needed. I've utilized iron router to create a unique URL for each instance of the form, enabling users to a ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPo ...

Is it possible to verify the necessary node_modules for the project?

Is there a more efficient method to identify and remove unnecessary node_modules packages from my create-react-app project, rather than individually checking all utilized packages and their dependencies? I'm hoping to trim down the project's siz ...

Javascript isn't being executed by Internet Explorer as expected

I'm currently working on a web application that requires backend processing while simultaneously showing the information on the screen. AJAX seems like the ideal solution, so I've implemented it in my project. However, before initiating the AJAX ...

The for loop in JavaScript fails to verify the contents of an array and instead shows a message in a designated

The message for leap year is not appearing in the designated element Uncertain why the message isn't showing after the for loop const year = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032]; for (var i = 0; i < ye ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

Tips for setting a uniform width for all bars in apexcharts bar column width

When working with dynamic data, the length of the data should also be variable. For instance, if the data has a length of 24, the column width should be 35px; similarly, even if the data has a length of 2, the column width should still be 35px. Apexchart ...

The authentication method "discord" is not recognized

Currently, I am working on implementing discord authentication using passport. Originally, everything was functioning correctly, but now it seems to have encountered an issue which I cannot identify. auth.js const express = require('express') co ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Tips for successfully typing the backtick character when transitioning to Typescript:

I am currently working on a Typescript Vue project involving Leaflet. I came across some code for lazy-loading map markers, but it was written in Javascript. Although the code works fine, I keep receiving errors and warnings from VSCode because this is not ...

Experience seamless navigation with Highstock's fluid panning feature

I'm attempting to achieve seamless panning on a basic highstock chart by clicking and dragging within the plot area. Interestingly, I have found that this works flawlessly when my data is not based on timestamps: data: [-25.1,-23.8,-19.9,-19.1,-19.1 ...

Guide to integrating Inversify with Mocha

In my TypeScript Node.js application, I am implementing Dependency Injection using Inversify. The functionality works perfectly during the app's execution. However, I encountered an issue with the @injectable() annotation when running tests. An error ...

Universal HTML form validation with a preference for jQuery

Is there a jQuery plugin available for form validation that follows the most common rules? Specifically, I need to validate based on the following criteria: All textboxes must not be empty If the 'Show License' checkbox is checked, then the &a ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

Adding a class-matched element with a corresponding ID

Despite finding similar questions, I am still unable to achieve the desired outcome. Here is a list: <ul> <li class="class1"></li> <li class="class2"></li> <li class="class3"></li> <li class="class4"&g ...

Is it possible for me to customize the default angular filter in order to prioritize displaying strings that begin with the search term?

In my current project, we are dealing with a massive list of strings (17,000+ at times) and have implemented an input box for filtering the list. Initially, I used Angular's default filter, but then a request came in to sort the list so that strings s ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

Retrieving variable values from a dynamic array

I'm struggling with setting a dynamic value within an Object. I am loading some data inside my created hook. created() { let vm = this; axios.all([ axios.get('/api/report/someUrl'), axios.get('/api/report/someUr ...