A guide on iterating through an array retrieved from the Vuex store

I am currently working with Vuex and VueJS 3, attempting to loop over an array from the Vuex store. However, I keep encountering an error that says the array is undefined. I have confirmed that the data is logging correctly, but when using it with the v-for directive, it throws an error stating it's undefined.

import { createStore } from 'vuex'

export default createStore({
  state: {
    AddTaskShown: false,
    Tasks: []
  },
  getters: {
  },
  mutations: {
      ToggleAddTask(state) {
      state.AddTaskShown = !state.AddTaskShown;
    },
    addTask(st, {name, description, date }) {
      st.Tasks = [...st.Tasks, {name, description, date}]
    },
  },
  actions: {
  },
  modules: {
  }
})

Here is the code for the store:

<template>
  <div class="grid grid-cols-1 gap-1 py-3">
    <Task :v-for="Task in $store.state.Tasks" :Task="Task" />
  </div>
</template>

<script>
import Task from "@/components/Task.vue";

export default {
  components: {
    Task,
  },
};
</script>

Below is the component code:

<template>
<div class="mx-5 my-1 bg-slate-700 p-4 text-white rounded-lg">
    <input type="checkbox" class="w-4 h-4 mr-2"> {{ Task.name }}
</div>
</template>
<script>
export default {
  name: "Task",
  props: {
    Task: Object,
  },
};
</script>

The error message I am receiving is:

Task.vue?c155:2 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
    at Proxy.render (Task.vue?c155:2:1)
    at renderComponentRoot (runtime-core.esm-bundler.js?d2dd:896:1)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?d2dd:5580:1)
    at ReactiveEffect.run (reactivity.esm-bundler.js?89dc:185:1)
    at instance.update (runtime-core.esm-bundler.js?d2dd:5694:1)
    at setupRenderEffect (runtime-core.esm-bundler.js?d2dd:5708:1)
    at mountComponent (runtime-core.esm-bundler.js?d2dd:5490:1)
    at processComponent (runtime-core.esm-bundler.js?d2dd:5448:1)
    at patch (runtime-core.esm-bundler.js?d2dd:5038:1)
    at mountChildren (runtime-core.esm-bundler.js?d2dd:5234:1)

Answer №1

To ensure the Tasks state is properly monitored for changes, it's essential to set it within a computed property. Without this, errors can occur as the template is executed before the Tasks state is initialized.

Another issue that arises is a naming conflict between the component name Task and the individual array item also named Task.

To resolve this, update the props name from Task to task

For better practice, always use camelCase when naming your variables.

<template>
<div class="grid grid-cols-1 gap-1 py-3">
    <Task :v-for="task in Tasks" :task="task" />
  </div>
</template>

<script>
import Task from "@/components/Task.vue";

export default {
  components: {
    Task,
  },
  computed: {
     Tasks() {
         return this.$store.state.Tasks
     }
  }
};
</script>

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

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Experiencing difficulties coding SVGs

Struggling with manipulating SVGs in JavaScript and looking to extend a line by clicking a button? Check out this code snippet I've included in the head tag: <script type="text/javascript"> x=135; y=135; var container = document.getElementById( ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

Removing an element in ReactJS

As a newcomer to React, I created an application that supports saving searches. Currently, it retrieves data from a static array data in JSON format. Unfortunately, I'm struggling with the process of removing saved searches from the list. You can vie ...

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

Is there a way to set a default value for an Angular service provider?

Imagine an Angular Service that encapsulates the HTTP Client Module. export class HttpWrapperService { private apiKey: string; } Of course, it offers additional features that are not relevant here. Now I'm faced with the task of supplying HttpWr ...

"Add a hover effect to fade the image and make it clickable for a

Is there a way to make the entire image a clickable link when it's hovered over, rather than just the text inside? I could use some assistance with this. Javascript: $('.thumbnail').hover(function() { $('.thumbnail img').stop ...

Unable to locate the 'isDirectory' property of an undefined value

This code example is showcased in the book titled SMASHING Node.js:Javascript Everywhere. Despite following the steps and entering node index in the terminal, I encountered the following error message: Cannot read property 'isDirectory' of und ...

Exploring vast data sets in PHP

Recently, I received an OO PHP application to analyze. Upon doing a print_r or var_dump of a large array in the codebase, it yielded over 18000 lines of output. Are there any online tools or classes available that can help me view and search through these ...

Exploring the use of multidimensional arrays in Objective-C

I received JSON data from the Google Speech API and converted it into an array using the following code: NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonResponse options: NSJSONReadingMutableContainers error: &e]; The current structu ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

Explaining the defineAsyncComponent Method in Vue 3

Recently, I've been exploring the vue3-beta release and stumbled upon a new feature called defineAsyncComponent. Surprisingly, there's not much information about it online. I'm curious about its use-case and when it should be used. How does ...

Sending decimal values between Arduinos is proving to be troublesome

I have a project where I need to transfer three float values from one Arduino to another and store them in an array on the receiving Arduino. However, when I print the received float values, I only see the first two digits in the serial monitor. As a begi ...

The `finally` function in promises is failing to execute properly

Currently working with Typescript and I've included import 'promise.prototype.finally' at the beginning of my index.js file (in fact, I've added it in multiple places). Whenever I try to use a promise, I encounter the error message say ...

VueJS Error: Unable to access the 'className' property of an undefined variable

I'm currently working on a menu design project where I need to highlight the active tab/page that the user is on by adding a color class and utilizing JavaScript to update the active link. Here's a snippet of my template: <div class="menu ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Developing a script to scan a document, save its contents into an array, and display the frequency of each word within the array

I'm looking to develop a function that can: Read a text file, process it word by word, and save the words in an array. Determine the frequency of each word and store each word only once in the array. Display each word with its frequency next t ...

Error encountered while converting JSON into an array in PHP index

Recently, I've been working with a JSON text that looks something like this: $text = '{"id": "12", "count": "1", "1": {"gkey": "g_c5218"}, "0": {"gkey": "g_4b4c6"}}'; My main goal is to convert this text into an array. Here's how I at ...

Having trouble populating data using JSON, the process is not functioning as expected

I need to dynamically populate a ul element with a list of options retrieved from JSON data. JSON Data: { "product": { "options":{ "42432":{ "id":42432, "title":"Choose your date", ...

Continue running web AJAX request in Android browser while it is minimized

I need help with my AJAX call var tid = setInterval(mycode, 2000); function mycode() { $.ajax({ url:'/ajx.php', type: "GET", success: function (data) { }, ...