Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API includes methods like: loadMemory, sleep, connectDevice. (Just for illustration purposes).

To maintain a global Vuex Machine object, I've set up an action to dispatch the initial creation and store the returned object like this:

actions: {
createChannel({ commit, state }, params) {
      m.createMachine(params).then(
        function (newMachine) {
          commit('setMachine', newMachine);
        }
      ).catch(err => { console.error("Error"); } )
    }
}

The mutation for this scenario is rather simple:

  setMachine(state, machine) {
      state.machine = machine;
    }

Since the API provides methods that alter the state of "Machine" objects but we're unsure which specific fields they modify, I aim to encapsulate them in actions.

An action might look like this:

this.state.machine.loadMemory(mem.addr)

If this call changes the machine object itself, how do I update the state? Should I clone the original object, apply the state-changing method, and replace the object?

I am aware that cloning is not a straightforward task.

Appreciate any advice.

Answer №1

If you need to re-mount your intricate object, consider using this mutation as a guide:

reloadMemory(state, newAddress) {
  const { device } = state;

  state.device = {
    ...device, // retain all properties of the device
    address: newAddress,
  };
}

This approach is applicable for any depth of nested objects. Here's another scenario:

reloadMemory(state, updatedValue) {
  const { device } = state;
  const { deviceProperty } = device; 

  state.device = {
    ...device, // retain all properties of the device
    deviceProperty: {
       ...deviceProperty, // retain all properties of the deviceProperty
       value: updatedValue,
    },
  };
}

Answer №2

To achieve this, one approach is by utilizing the lodash method called cloneDeep. This function allows for a deep copy of an object's properties and methods.

import _ from lodash

this.state.machine.loadMemory(mem.addr)
const copiedMachine = _.cloneDeep(this.state.machine)
this.$store.commit('setMachine', copiedMachine)

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

Displaying Angular JS data in the Laravel application using the URL::route facade

I'm currently working on an Angular JS + Laravel Application. On one of the pages, I have a list of users that I fetch, and when a row is clicked, it redirects to the edit user page. Below is a snippet of my code: Blade Template <tbody> &l ...

To resolve the issue in Node, address the following error message: "User validation failed: username: Path `username` is required. Password: Path `password` is required."

I am currently in the process of creating a new user and verifying if the user's email already exists. If it does not exist, a new user is created and saved. Can anyone help me identify and correct the validation error I am encountering? I have attem ...

Nuxt generate encountered an error: Unable to access the property 'normalModuleFactory' as it is undefined

Just recently, I decided to upgrade Nuxt from version 1.4.0 to 1.2.x and Vuetify from 1.0.9 to 1.2.x. Everything seemed fine when running npm run dev after the update. However, when I attempted to run Nuxt generate, an unexpected error occurred. I've ...

Consolidate and then transfer to a different database

How can I insert the data returned from my aggregate (controller function) into another collection called User? Here is the schema for the User: const userSchema = new mongoose.Schema({ firstName: { type: String, required: [true, &ap ...

What is the reason behind Angular's repeat filter only being able to access its own element within the return function?

I have successfully implemented some Angular code that is working, however, I am struggling to understand why it works. Coming from a C Sharp background and being new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | ...

How can I navigate between pages without losing the data entered in the form fields

Is there a way in Ajax or jQuery to save form data and navigate between multiple form pages without using PHP Sessions? I want the form data to be saved until the user submits it, and when they do submit, all information from different pages should be in ...

Can a value of a variable be "stored" in NodeJS?

I am working on a website that allows clients to make their site go live by setting var live = true;. Once this variable is set, certain webpages will display. I would prefer not to store the live variable in a database as creating a collection solely fo ...

Nuxt 3 turns a blind eye to TypeScript errors upon code saving

I am facing an issue. Even with a TypeScript error in the code, the IDE shows an error, but I am still able to save it and run it in the browser. Is this acceptable? Check out the code below: <script lang="ts" setup> const a = ref<strin ...

Which JavaScript objects contain the addEventListener method within their prototype?

I am aware of the following: Element.prototype.addEventListener Window.prototype.addEventListener Document.prototype.addEventListener Are there any more? ...

Having trouble with importing files from a different folder in a React Typescript project

I have a specific folder arrangement set up https://i.sstatic.net/GFOYv.png My goal is to bring both MessageList.tsx and MessageSent.tsx into my Chat.tsx file // Chat.tsx import React from 'react' import {MessageList, MessageSent} from "./ ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

"error: unable to retrieve message channel name, result is undefined

Hey there, I'm currently experiencing an issue while trying to retrieve the name of a channel that I created. Strangely enough, it's returning undefined, even though I am certain that the channel exists. Let me share with you the code snippet wh ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Is it possible for a memory leak to occur in node.js when using new Date()?

For this particular case, when updating an existing MongoDB document with new Date() causing a potential memory leak is a question that arises. One might wonder if allocating a new object with the new keyword necessitates manual deallocation to prevent lea ...

Troubleshooting ER_BAD_FIELD_ERROR in a node mysql stored procedure

Encountering an error message while executing the following code: Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list' Output: { employee_id: '6', employee_name: 'test', employee_contact: ...

Add a new variable to the data in a jQuery ajax request for each request with any updates

I've encountered an issue with the code below, which is meant to add additional data to any ajax request made by my app. It works fine when the page first loads, but because my application is single-page and ajax-based, I need the updated variable val ...

The process of generating vue-cli-plugin-prerender-spa encountered an issue where the error was not found within the

I have successfully integrated this plugin into my laravel-vue application and configured it within the laravel mix's webpack.mix.js file. After running it via npm (using watch, dev, and prod modes), I encountered no errors. However, upon inspecting ...