What is preventing me from using bracket notation with a variable to assign a property to an object?

I am a complete beginner when it comes to Vuex, and I am currently facing an issue with assigning a value to a Vuex state, specifically state.map.status.isReady.

To make my code more reusable, I decided to create a function called

changeMapStatus(state, key, value)
to handle this task.

This function is meant to update the property state.map.status.key with the value it receives.

However, when I try to call the mutation using

this.$store.commit('changeMapStatus', 'isReady', true)
from a component file, it somehow removes the existing state.map.status.isReady and sets it to undefined.

On the other hand, if I modify the function to look like this:

changeMapStatus(state, value) {
  state.map.status.isReady = value;
}

it seems to work fine.

Can someone point out where I might be going wrong?

Thank you in advance!


store.js (Vuex)

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    map: {
      status: {
        isReady: false,
      },
    },
  },
  mutations: {
    changeMapStatus(state, key, value) {
      state.map.status[key] = value;
    }
  },
});

Answer №1

As per the Vuex official documentation, a mutation in Vuex requires two parameters: state and payload. Utilizing the spread operator allows you to extract values from the payload.

modifyMapState(state, {key, value}) {
  state.map.state[key] = value;
}

this.$store.commit('modifyMapState', {key: 'active', value: true})

Alternatively, you can implement it in the following way

modifyMapState(state, payload) {
  state.map.state = {
      ...state.map.state,
      ...payload,
  }
}

this.$store.commit('modifyMapState', { active: true });

Answer №2

To utilize an object as a parameter with both a key and value, you can do the following:

updateStatus(state, obj) {
  state.data.status[obj.key] = obj.value;
}

Then, you can call this function like this:

this.$store.commit('updateStatus', {key:'isActive', value:true})

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

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

JSON data is returned as Object Object

Trying to work with a JSON object and need to stringify it for localStorage: $http.post('http://localhost:8000/refresh', { name: $scope.name, email: $scope.email, token: $rootScope.devToken, platform: ionic.Platform.platform() }).then( ...

Updating the state in a React array of objects can be achieved by checking if the specific id already exists in the array. If

In the scenario where the parent component receives an object from the child component via a callback function, I need to verify the existence of an object with a specific rowID. If it exists, the object should be updated with the passed value "val"; oth ...

Losing values due to custom $validator and getterSetter in AngularJS / UI Bootstrap

My objective is to create a UI Bootstrap datepicker with an input mask feature. The datepicker directive only validates dates selected using the popup window and not dates manually typed in by the user. To address this, I researched how to implement custo ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

Optimizing performance: Making the most of mongoose updateMany middleware

PROBLEM SOLVED: SOLUTION PROVIDED BELOW I have a piece of code where I am updating elements one by one: //registerCustomers.js const CustomerRegistrationCode = require("../models/CustomerRegistrationCode"); const setRegCodesToUsed = async (regC ...

The md-select search filter currently functions according to the ng-value, but it is important for it to also

I am using a md select search filter with multiple options available. For instance: id: 133, label:'Route1' id: 144, label:'Route2' id: 155, label:'Route3' id: 166, label:'Route4' If I input '1' ...

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

Nothing is in the Laravel array when using `$request->all()`

In the process of developing a shopping cart using Laravel. Here are the details : Routes : Route::post('/cart/add', 'CartController@store')->name('cart.store'); Route::patch('/cart/{product}', 'CartContro ...

A guide on dynamically loading images based on specified conditions in AngularJS

I am trying to display different images based on a value. If the value is greater than 3.50, image1 should be shown; if it is equal to or less than 3.50, image2 should be shown. I have attempted to write this code but I cannot find where I made a mistake. ...

Understanding how objects are created using the reduce method

I'm curious about how the reduce function can transform an array into an object as shown in this example, particularly with the line: p[c[0]] = c[1]; Is this an unconventional syntax for creating key-value pairs that I haven't encountered before ...

javascriptEmbed youtube video thumbnail dynamically as users input a URL

I am currently working on a React frontend for my web app. One of the features I want to implement is a URL input box, with an image display panel below it. The goal is that when a user enters a YouTube URL into the input box, the thumbnail of the correspo ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...