Tips for utilizing the MutationAction feature in vuex-module-decorators

I am currently exploring the functionality of vuex-module-decorators found at . Suppose my module's state includes a property called dir which is a dictionary structure: {[key: string]: string}. Can I utilize @MutationAction to update an element within that dictionary? The code example below may not be correct, but it attempts to convey my intentions.

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @MutationAction(???)
  updateDir(keyValue) {
    return keyValue // ???
  }
}

Is there any documentation available on how to properly use @MutationAction, including what arguments it accepts and what actual mutation it triggers?

Answer №1

Check out the recommended approach below -

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @MutationAction(['dir'])
  async updateDir(keyValue) {
    const currDir = this.dir

    // perform any asynchronous tasks (like network requests) here
    currDir['myKey'] = keyValue

    return ( { dir: currDir } )
  }
}

However, if you don't have any asynchronous tasks to handle initially.

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @Mutation
  async updateDir(keyValue) {
    this.dir.myKey = keyValue
  }
}

P.S. The creator of vuex-module-decorators also authored this content.

Answer №2

As a newcomer to vuex, I managed to get this code working:

export class MyModule extends VuexModule {

    public dir: { [key: string]: string } = {};

    @MutationAction({ mutate: ['dir'] })
    public async updateDir(key: string, value: string) {
        const newDir: { [key: string]: string } = {};
        newDir[key] = value;
        return {
            dir: newDir,
        };
    }

    @MutationAction({ mutate: ['dir'] })
    public async addToDir(key: string, value: string) {
        this.dir[key] = value;
        return {
            dir: this.dir,
        };
    }
}

I'm unsure if it's recommended to modify and reassign the 'dir' variable like I did in the second method.

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

When integrating external HTML into an Angular 2 component, relative references may become invalid and fail to

My server hosts basic HTML content that includes an image with a relative file location. While this displays correctly in a browser, loading the content using Angular causes issues with resolving the relative path locally. I have tried following suggestio ...

A universal function that uses an array parameter to create a custom type

My function takes an array as a parameter and constructs the generic type passed in by the array. Everything is working fine, but I want to add a type check to ensure that the keys of the array match the properties of the generic type, otherwise it should ...

Update the @Input field within an @Component following the completion of an Http Request in Angular2

I am currently developing an application using Angular2. One of the components has a button that, when clicked, triggers a post request to the server. The server will then respond with either an Ok(string) or a BadRequest(string). I am facing difficulties ...

How can debugging in Chrome be achieved using Typescript?

How is it possible to debug TypeScript in Google Chrome when the browser only understands JavaScript? I find myself debugging my TypeScript files within my Angular project, which was created using Angular CLI, through the Chrome developer tools. However, ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

The Vuex mutation does not execute synchronously and does not resolve as a promise

My vuex mutation doesn't work synchronously as expected. Here is the code: mutations: { computeStatusData(state, status) { if (status.active !== true) { return } const started = new Date(status.startedAt); started.setHour ...

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...

When using MERN Stack (with Typescript) on DigitalOcean, encountering an issue where HTML files are displayed instead of JS and

Upon checking the console, I encountered this https://i.sstatic.net/PWoT5.jpg The app has been developed using Ubuntu and Nginx so far with no firewall configuration yet in place. This is my first time deploying a MERN stack and utilizing DigitalOcean. ...

Ways to effectively implement the setState function through the use of the useDerived

While attempting to pass the translateX.value to the parent using setXPos, I encountered an error stating "Tried to synchronously call function {bound dispatchSetState} from a different thread." Even though I tried using runOnJS(setXPos)(event.translatio ...

Steps for activating the HTML select option menu with an external button click

I'm currently in the process of building a React website and I'm faced with the challenge of customizing select options to align with my design in Figma. Check out this image for reference Here's how I've set it up in my code: const C ...

How can we implement type guarding for a generic class in TypeScript?

Implementing a generic class in TypeScript that can return different types based on its constructor parameter. type Type = 'foo' | 'bar'; interface Res { 'foo': {foo: number}; 'bar': {bar: string}; } class ...

Exploring the ngModel directive implementation within a text input field

I'm facing an issue with displaying data in input forms. <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text text-white" style="background-color:#03a9f4">Product ID</span& ...

Utilizing personalized sorting for arrays of objects in TypeScript

I have an array of objects in my Angular Project that require custom sorting techniques. For example, each object contains the properties id and category. let cars: { id: number, category: string }[] = [ { "id": 3, "category": "fast car" }, { "id ...

Utilize static members of an imported type within an Aurelia view

Currently, I am utilizing Aurelia in combination with TypeScript. In my code, I have defined a simple type with static variables as shown below: export class MyModule { static foo = false; } Furthermore, I have created an Aurelia view model as follo ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

Cease the interval once the array is devoid of elements

I'm currently working on simulating typing effects for incoming server messages by adding an interval to the output. Here's what I have so far: const stream = interval(1000) .pipe( map((): Message => { return messages.pop(); }) ); ...

webpack is having trouble locating the src file, even though it should not be searching for it in the first place

I'm currently delving into the world of using TypeScript with React and am following a helpful tutorial at: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614 However, when attempting to run the webpack command thr ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...

What is the process for importing a TypeScript module from the local directory?

I am currently working on a TypeScript module with plans to eventually release it on NPM. However, before publishing, I want to import the module into another project hosted locally for testing purposes. Both projects are written in TypeScript. The TypeSc ...

Sending a specific object and its corresponding key as parameters to a reusable component in Angular: T[K]

I am currently working on developing a generic component in Angular and Typescript version 4.4.4. The goal is to create a component where I can set both an object (obj) and specific keys (properties). Here's a simplified version of my text component: ...