Unable to retrieve Object property using computed method in Vue 3 vuex results in undefined value

When attempting to display the values of a computed property in the template using the syntax {{todo[0]['title']}}, I am receiving an 'undefined' output. However, using {{todo[0]]}} allows me to render the entire object. My goal is to be able to render a todo using its property specifically. Any help or guidance on this matter would be greatly appreciated.

const {
  createApp,
  ref,
  computed,
  onMounted
} = Vue;
const {
  createStore
} = Vuex;
const store = createStore({
  state: {
    alltodos: []
  },
  mutations: {
    setTodos(state, todo) {
      (state.alltodos) = todo
    }
  },
  getters: {
    allTodoGetters(state) {
      const sta = JSON.parse(JSON.stringify(state));
      return sta
    }
  },
  actions: {
    async fetchTodos({
      commit
    }) {
      const response = await axios.get('https://jsonplaceholder.typicode.com/todos');
      commit('setTodos', response.data);
    },
  }
});
const app = createApp({
  setup() {
    let alltodos = computed(() => store.getters["allTodoGetters"]);
    onMounted(() => {
      store.dispatch('fetchTodos')
    })
    return {
      alltodos
    }
  }
});
app.mount("#app")
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.30/vue.global.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdcbc8d8c5fd89938d938d">[email protected]</a>/dist/vuex.global.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="app">
  <div v-for="(todo, index)  of alltodos" :key="index">{{todo[0]}}</div>
</div>

Answer №1

To display the first item from an array, you can use the code snippet below:

const {
  createApp,
  ref,
  computed,
  onMounted
} = Vue;
const {
  createStore
} = Vuex;
const store = createStore({
  state: {
    alltodos: []
  },
  mutations: {
    setTodos(state, todo) {
      (state.alltodos) = todo
    }
  },
  getters: {
    allTodoGetters(state) {
                                                // 👇 return just the state you want
      const sta = JSON.parse(JSON.stringify(state.alltodos));
      return sta
    }
  },
  actions: {
    async fetchTodos({
      commit
    }) {
      const response = await axios.get('https://jsonplaceholder.typicode.com/todos');
      commit('setTodos', response.data);
    },
  }
});
const app = createApp({
  setup() {
    let alltodos = computed(() => store.getters["allTodoGetters"]);
    onMounted(() => {
      store.dispatch('fetchTodos')
    })
    return {
      alltodos
    }
  }
});
app.mount("#app")
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.30/vue.global.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="552320302d15617b657b65">[email protected]</a>/dist/vuex.global.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="app">                           
  <div v-for="(todo, index) in alltodos"  :key="index">
           <!-- 👇 show property you want -->
    <div v-for="(property, i) in todo">{{ property }}</div>
  </div>
</div>

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

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

Leveraging React's State Values and Props

Can you help me with a React component challenge? I have two components that I need to work with: <select> <mytable> I want to build a new component called <myInterface>. The state of <myInterface>, let's call it S, needs to ...

Retrieving the output of an asynchronous function within another function in JavaScript

I'm facing an issue with the Chrome API functions being asynchronous, making it difficult for me to get their return value. Here's a snippet of code that demonstrates my problem. I'm working with AngularJS. $scope.storageGet = function( ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Tips for effectively invoking a method in a Vue component

As a Vue2 beginner, I am currently working with the Vue CLI and following the structure generated from it. My goal is to submit form data, but I keep encountering a warning and error: [Vue warn]: Property or method "onSubmit" is not defined on the insta ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

Exploring the possibilities of ReactJS and the sleek design of

How can I alter the background color of a RaisedButton without having the CSS class name appear in the autogenerated div? Here is the button: <RaisedButton className="access-login" label="Acceder" type="submit"/> This is the specified CSS: .acces ...

Switching the class of a navbar button in Vue.js based on the current page

My webpage has a fixed navbar at the bottom implemented in the App.vue component to ensure it appears on every page. I am seeking a solution where the button in the navbar corresponding to the current page highlights or changes its class when a user naviga ...

Error encountered during decryption with AES encryption: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'

I am attempting to decrypt data retrieved from MongoDB using a key and initialization vector (IV) that were stored in an environment function. However, I keep encountering the following error: ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH app.get("/recieve", as ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Implementing ajax functionality for a form component in vuejs

I am currently working with a Vue.js component that serves as a form with a single field for an email input. The default value of this field, "email", is provided to the component by the parent as a prop. Upon form submission, I need to trigger an event to ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

Dragging a stack of cards in a game of Solitaire using jQuery UI

I'm currently in the process of creating a Solitaire card game using Javascript. To enable dragging and dropping functionality for the cards, I am utilizing jQueryUI. In the example provided at http://jsfiddle.net/HY8g7/1/, you can see how the cards c ...

Arrays of objects arranged within other arrays with the use of v-for

Struggling with a tricky problem here... I'm having difficulty displaying nested for-loop data: <div v-if = "private.folders!=null" v-for="folder in private.folders"> {{folder.name}} <div v-for="check in folder.checks"> {{chec ...

Exploring the Boundaries of JavaScript Libraries

Exploring the inner workings of JavaScript libraries has been a challenge for me. Despite having some background in Java and JavaScript, I find the code below quite perplexing. These snippets are extracted from an example on david-tang.net's website. ...

The Ajax request keeps encountering a bad request error despite it working perfectly fine in Postman

After spending hours conducting extensive research and trying various methods without success, I am still unable to obtain a JWT token after providing the user and password. function listenForLogin() { console.log('listening') $('# ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Display sub navigation when clicked in WordPress

I currently have the default wordpress menu setup to display sub navigation links on hover, but I am interested in changing it so that the sub navigation only appears when the user clicks on the parent link. You can view my menu here https://jsfiddle.net/f ...

Reference loss occurs in Angular Ionic when using @ViewChild

This situation is straightforward I am dealing with a reference in this format @ViewChild('myElement') myElementVar : SomeClass; The element I am referencing appears like this <element #myElement *ngIf="someBoolean"></element> As ...

AngularJS encountered an error: The token '|' was unexpected and expected ':' instead

My HTML file contains a condition where certain fields need to be displayed automatically in landscape mode using filters. However, when I run the program, I encounter the following code: <tbody> <tr ng-repeat="ledger in vm.ledgers ...