Tips for effectively utilizing Vuex to manage items within a Vuetify data table

I am currently sending an API request to retrieve an array of objects that has the following structure:


returnedItems [
        {
         name: 'Adam', 
         age: '30', 
         interest: 'Sports'
         },
         {
         name: 'Emily', 
         age: '22', 
         interest: 'Reading'
         }]

My goal is to store this data in Vuex and utilize getters and setters to showcase the information in a Data-Table component, but I am unsure about the process.

Here is a snippet of my Data-Table component:


 <template>
<v-data-table :headers="columns" :items="tableData">
  <template v-slot:items="props">
     <td>{{props.tableData.name}} </td>
      <td>{{props.tableData.age}} </td>
   </template>
</v-data-table>
 </template>

 <script>
   import { mapGetters } from 'vuex'
   export default{
       data() {
         return {
           columns: [
           { text: 'Name', sortable: false },
           { text: 'Age', sortable: false },
           { text: 'Interest', sortable: false },
               ]
          }
         }
       },
      computed: {
         ...mapGetters({ 
       tableData: 'tableData'
       })
          }
 </script>        

Furthermore, here is how my store is structured:


     state: {
     items: []
    },
    getters: {
      tableData: state => state.items
    }

If my approach is incorrect or if I need to implement mutations, any guidance would be highly appreciated. Thank you for your support.

Answer №1

If you want to bring about changes in a Vuex store, creating mutations is essential. These mutations allow you to alter the state of the store effectively. Here's an example of how you can set up your mutations:

const mutations = {
    setItems: (state, payload) => {
        state.items = payload;
    }
}

It's important to note where you are invoking your API from. Consider using Actions for this purpose. Unlike Mutations, Actions offer asynchronous capabilities, making them suitable for API calls.

const actions = {
    setItems: (context, payload) => {
        //When a payload is included, it will be committed to the "setItems" mutation
        if (payload) {
            context.commit("setItems", payload);
            return;
        } else {
            //In case no payload is provided, an API call will be made
            Vue.$http.get(`https://example.com/getItems`).then(
                (response) => {
                    context.commit("setItems", response.body);
                },
                (error) => {
                    console.log(error);
                }
            );
        }
    }
}

Furthermore, if you simply need access to the state without any modifications, consider using mapState directly instead of mapGetters. The latter is more suited for scenarios where you require manipulated data while keeping the state unchanged, such as multiplying a state value by 3.

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

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

Tips on setting up and managing configuration and registering tasks in Grunt

I've been working on a project that involves using grunt to process my Js and SASS files. The issue I'm facing is that every time I need to make a change, I have to run all the tasks in my gruntfile.js, even if it's just for one module or th ...

A step-by-step guide on retrieving information from Material UI components and incorporating an onSubmit feature to transmit data to the backend server

I've recently started working with react/material-UI. While working on a project, I turned to youtube videos and various resources for guidance. I opted for material-UI due to its user-friendly nature. However, I'm currently facing a challenge ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Issue with Three.js failing to display textures

I'm a beginner with three.js and I'm struggling to get my texture to render properly in my scene. Despite following the documentation closely, all I see is a blank canvas with no errors in the console. Can anyone offer any guidance on why my code ...

What is the best method for creating thumbnail URLs for video files in HTML with JavaScript?

I am facing an issue with generating a thumburl for uploaded video files. After dynamically creating an input file and uploading local video files, I am able to retrieve the name and size of the file along with other information as shown in the screenshot ...

Challenges with the height of the calendar component in Vuetify

I need assistance with preventing the appearance of two scroll bars while working with Vuetify's sheet and calendar components. https://i.stack.imgur.com/yBfhj.png Below is my code snippet: <template> <v-app> <v-main> & ...

Collaborating on a single instance across several processes

I have a messaging bot in my project, where the connection is established using a class instance. class MessagingBot { public bot; constructor() { this.bot = new TelegramBot(); } } export default MessagingBot; In another file, I create an inst ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

"Trouble with kendo drop-down list: onclick event not triggering when text is changed

I am currently working with kendo UI and have implemented a dropdown list of checkboxes. The onchange event is triggering when the user clicks on the checkbox, but it is not firing when the user clicks on the text. Thank you in advance for your assistance ...

Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document. This is my attempt to make the call: function httpGet(){ var theUrl = "https://lo ...

Could you provide suggestions on how to update the content of an HTML tag within a Vue component?

I am new to Vue.js and struggling to grasp its concepts. I am interested in finding a way for my custom Vue component (UnorderedList) to manipulate the content within it. For example, if I have <p> tags inside my component like this : <UnorderedL ...

Mapping JSON data with an elastic search cluster can be challenging, especially when dealing with a dynamic number of fields

I am currently developing an application where I need to map JSON data for storage in Elasticsearch. The challenge is that the number of fields in the JSON data is dynamic. How can I handle mapping in this scenario? Mapping Snippet var fs = uploadedFiles ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

Encountering an unexpected or invalid token in line 1 after reinstallation of Windows can be a frustrating experience

Yesterday, my JavaScript file was running smoothly. However, after reinstalling Windows and Node, I'm encountering an error when trying to run the same JavaScript file today. $ node index.js C:\Users\<user-name>\Google Drive&bsol ...

Self-moving button container

I have a challenge involving a button and a sliding div. When the button is clicked, I want the div to slide. The problem arises when I place the button inside the sliding div - it ceases to slide. I understand the issue at hand, but I'm unsure of ho ...

What is the best way to move the Grid upward when the above content is not visible?

Let me demonstrate what I have been working on. Currently, I am creating a weather application to explore the functionalities of https://material-ui.com/. I am attempting to prototype an animation inspired by Google Flights, which can be seen here: https: ...

What is the process for generating an HTML document from start to finish with the 'html-element' node module?

Here is an example that demonstrates a flawed method: const HTML = require('html-element'); const doc = `<body> </body>`; const page = HTML.document.createElement(doc) page.appendChild('<div>1</div>') page.append ...