Optimal method of creating and initializing store items in Vue using Vuex

As a newcomer to Vue, I am exploring the best approach to manipulate a "master" store object by stripping keys, renaming others, and creating an altered version to save as a new store item.

In my App.js file, I initiate a "loadData" action within the created() lifecycle hook and then call a local function 'prepareData' to modify the mapState["eventsData"] and generate two new store items.

The issue I'm encountering is that the original "master" eventsData object is being altered by my functions. Additionally, upon the initial page load, this.eventsData (the main object) is displayed as [__ob__: Observer], only showing the data on subsequent loads when pulled from localStorage.

App.js (prepareData() method involves adjusting key/value pairs).

export default {
  name: "App",
  data() {
    return {
      calendarData: [],
      gridData: [],
    };
  },
  computed: mapState(["eventsData"]),
  created: function () {
    state.commit("initializeStore");
    this.$store.dispatch("loadData"); // Fetches data and commits "setEventsData"
    this.prepareData();
  },
  methods: {
    prepareData() {
      this.calendarData = this.eventsData.forEach((event, i) => {
        delete event.artist_supporting;
        delete event.genre;
        // Additional key manipulations...
      });
      this.gridData = this.eventsData.forEach((event) => {
        // Additional key manipulations...
      });
      state.commit("setCalendarData", this.calendarData);
      state.commit("setGridData", this.gridData);
    },
  },
};

index/store.js

 mutations: {
    initializeStore(state) {
      // Retrieves data from localStorage or sets to empty array
    },
    setEventsData: (state, data) => {
      // Sets eventsData in state and updates localStorage
    },
    // Additional mutation methods...
  actions: {
    loadData({ commit }) {
      // Fetches data from external source and updates store
    },
  },

Answer №1

Let's start by addressing a few key points:

Within the created() method of App.js, I trigger a "loadData" action and then invoke a local function called 'prepareData'.

However, there is an issue here. The axios call operates asynchronously, meaning that you do not wait for it to complete before calling your prepareData() method. To rectify this, consider the following solution:

loadData({ commit }) {
    return axios
        .get("/data/eventsData.json")
        .then((response) => {
            commit("setEventsData", response.data);
            commit("setLoading", false);
        })
        .catch((error) => {
            console.log(error);
        });
}
this.$store.dispatch("loadData").then(() => {
    this.prepareData();
});

Furthermore, performing this operation within your Vue component may not be ideal. It is recommended to move this logic to your store and call it within the then block of your axios call. This approach simplifies data refreshing from other components and keeps your Vue file concise.

Additionally, I advise against using the delete keyword, as it may lead to unintended object mutations within the eventsData array due to shared references. Instead, opt for creating a new object using the ES6 spread operator syntax.

Lastly, have you considered utilizing a Vuex getter instead of storing a modified version of the eventsData array?

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

Teaching the render engine: The process of ReactJS guiding the render engine through updating the DOM component

I recently learned that ReactJS utilizes Virtual DOM to efficiently compare and update only the necessary parts of the actual DOM node, rather than refreshing all nodes. It's interesting how React instructs the render engine to target specific nodes f ...

Stopping autoplay in React Swiper when hovering over it

I'm currently struggling to find a way to pause the autoplay function on swiper when hovering over it. Despite my efforts, I have not been able to locate a solution. <Swiper spaceBetween={0} navigation={{ ...

Issue with Angular table display cell overloading(produces excessive rendering of cells)

In my project, I am working with 3 arrays of data - DATA_CENT, DATA_NORTH, and DATA_WEST. Each of these arrays contains another array called data, which I need to extract and display in a table format. For each new column, I create a new table and then po ...

Styling Bootstrap radio toggle buttons using CSS

I am currently utilizing Bootstrap version 3.37 and have implemented two toggle buttons for users to select from. My goal is to have the "active" state assigned to the blue button when clicked, displaying a dark color. Conversely, when the green button is ...

Three.js: Transparent background for background elements and png particles

I'm struggling with making the background invisible and setting the alpha channel on my particles. I was hoping to use your example script wegl_particles_sprite for the Christmas season. I adjusted it to fit my needs by placing it in a fullscreen div ...

Polymer Google Maps Marker OnClick Function

I am struggling to trigger a click event for a google maps marker while utilizing the Polymer web component. After reviewing this question on Stack Overflow, I have noticed a minor difference in my code that may be causing issues. My implementation invol ...

Make your CSS and JS files smaller by using a PHP compression script in your WordPress child theme

  I am looking to implement a PHP script that will serve combined, pre-gzipped, and minified JS and CSS files. You can find the source code for this script here: https://code.google.com/p/compress/ I have a WAMP localhost with WordPress install ...

Switch the background image of a link within an accordion with a simple click

I'm attempting to create a toggle effect for a background image on a links within an FAQ accordion using javascript. After referencing this jsfiddle example (http://jsfiddle.net/QwELf/), I was able to get things to function. You can view my page in ...

Exchange the draggable elements between distinct div containers while keeping them in their original positions

Attempting to create an example showcasing Draggable jQuery with Bootstrap, everything is functioning smoothly so far. However, there are two things I am aiming to achieve: Swap the divs <div class='col-sm-12'></div> that were gen ...

PHP code to export data to a CSV file containing Chinese characters

I attempted the following: $name = iconv("utf-8", "GB18030", $value["name"]); Opening in a text editor and changing the encoding Importing into Excel while adjusting the encoding This process involves PHP and JavaScript: Here is my PHP code: echo & ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Creating a File and Resource Manager for Your Express Application: Step-by-Step Guide

I'm interested in creating a website section where users can upload files, such as game mods, for others to download. I envision this section being able to handle a large volume of files and users. How can I achieve this scalability and what architect ...

JQuery does not immediately update the input value

I'm working on a jQuery placeholder that mimics the behavior of default placeholders in Chrome and Firefox for browsers that don't support it. However, I'm facing an issue where the placeholder div's HTML doesn't change as quickly ...

Issue with promises in angular.js + node.js/electron integration is causing malfunctions

I have integrated angular.js with electron and node-orm to communicate with a database. The find/get functions in Node-orm are asynchronous, so I attempted to use Promises in a service to retrieve data like this: app.service('SearchService', fu ...

Is there a way to access the userID in the React.js front-end?

As I work on completing my Full Stack Web app with JWT token authentication based on roles, I find myself facing challenges with the front-end development. Specifically, I am unsure of the best practice for retrieving the UserID in the front-end to facil ...

Using jQuery to remove any HTML tags from user input

I have multiple inputs with text, but they are displaying with unwanted HTML tags. I attempted various solutions without success. Below is my jQuery code to extract data from a table: $(editModal+" #Website").val(n);; Here is an example of my input code: ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

Instructions on submitting a second AJAX form generated from the result of the first form submission

I loaded a form through an AJAX request in JSON format. The PHP code below generates the JSON output displaying the form: $this->errors[] = "<form id='confirmreset' name='confirm_reset' action='" . URL . "login/forgotPass ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...

Hide an Angular button when a page is loaded, depending on the information found in a table

How can I hide the Submit button in a table row if a certain condition is met based on information from the database? I attempted to create a function that returns true or false, but it ends up crashing my program because it runs continuously. I also trie ...