Vue3/Vuex - Issue with state change not being reflected in component when utilizing object destructuring

While working with Vue 3 and Vuex, I encountered an issue where Vue did not react to a state change when using object destructuring assignment to mutate the state. However, I found that Vue does react when the state is mutated by a mutation that only reassigns a single value.

Could I be doing something incorrectly?

The code snippet below successfully works

In my component, I accessed a Vuex getter in the setup() function:

const someValue = computed(() => store.getters['app/getSomeValue'])

The following code dispatches an action that mutates the value:

store.dispatch('app/setSomeValue', newValue)

Here's the corresponding mutation:

setSomeValue(state, value) {
  state.someValue = value
},

The subsequent code does not yield the expected result

If I wanted to update multiple properties of a module's state without resorting to multiple mutations, I would typically use object destructuring. In this case, the state changes when logged, but neither the component nor Vuex devtools acknowledge the change.

  1. The dispatched action:
store.dispatch('app/setSomeValue', { someValue: newValue })
  1. The mutation utilizing destructuring:
setState(state, payload) {
 state = { ...state, ...payload }
}

Even though I didn't need to modify the getter, Vue fails to detect the change when employing this approach. Upon logging the state after using destructuring, it reflects the updated value for someValue. Why isn't Vue recognizing this change?

Answer №1

It seems like reassigning the entire state object is hindering reactivity and causing Vuex to lose track of state changes in some way.

You can avoid this issue by using Object.assign to copy key-value pairs from your payload to your store's state, while preserving the original state object in memory.

setState(state, payload) {
  Object.assign(state, payload)
}

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

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

Incorporate SCSS variables directly into Vue single component files for easy reuse

My goal is to package a repository in npm that holds a directory of Vue single file components, which can be easily imported like so: import { Button } from "@user/design-system" The issue at hand is that the Button.vue file contains variables sourced fr ...

Sort through the API's array

Currently, I am working with the OpenWeather API's 5-day 3-hour forecast feature and encountering an issue regarding the response JSON. The array contains 40 items, each with a "dt_txt" value in the format of "2018-11-22 15:00:00". My goal is to displ ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

Executing Function when Vue JS Input Loses Focus

Hey there, I have a quick question regarding Vue JS. So, on my website, I have a shopping cart feature where users can enter any quantity. The issue I'm facing is that every time a user types a digit in the input field, the save method gets triggered. ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Utilizing THREE.js to guide a camera along a designated route

I'm currently working on developing a game using THREE.js. The game involves a path that consists of various curves and some straight paths. After finding an example online, I attempted to incorporate TrackballControls.js into the project to enable t ...

The text manipulates the canvas position and changes the location of mouse hover interaction

I am trying to achieve a similar header layout like the one shown on this page. However, when I insert some text within the header section: <div id="large-header" class="large-header"> <h1 style="font-size:150%;">Dummy Text</h1> ...

What is the best way to implement authentication on a Vue component in Vue.JS 2?

My view blade appears as follows: @if (Auth::user()) <favorite :id="{{ $store->id }}"></favorite> @else <a href="{{url('/login?red='.Request::path())}}" class="btn btn-block btn-success"> <span class="fa f ...

Tips for creating a nested array in Javascript:

Given the following: var person = {name: "", address: "", phonenumber: ""} I am trying to implement a loop to gather user input (until they choose to stop inputting information by entering nothing or clicking cancel). My goal is to utilize the person obj ...

Perform a sequence of test functions to display as individual tests on BrowserStack

I am faced with a challenge in my web application where I have a series of functions that simulate login and run through various features. These functions are written in JS using nightwatch.js and selenium via browserstack. The issue is that all the func ...

Having trouble with Vuex actions. Getting an error message that says "Failed to signInWithEmailAndPassword: The first argument "email" must be a valid string."

I recently started exploring Vuejs state management. I attempted to create a login system with Firebase using Vuex. However, I encountered the following error: signInWithEmailAndPassword failed: First argument "email" must be a valid string I'm havi ...

What is the integration process for jTable and Symfony 2?

After creating a Datagrid using jTable, I have included my JavaScript code in twig: <script type="text/javascript> $(document).ready(function () { jQuery('#grid').jtable({ title: 'Table of products', ...

The issue arises when attempting to use the cancel button to exit the editing modal for an item within an ng-repeat loop, while

In my project, I have set up a ng-repeat loop to display blocks that can be edited in a modal window. The goal is to allow users to make changes and then cancel the window to discard any modifications. While the modal window is functioning correctly and ed ...

Utilizing meteor to display information from a deeply nested collection

I've been struggling to extract data from a nested collection without success, as the dot notation in the HTML is not yielding any results. Essentially, my goal is to only retrieve the necessary data from a nested collection. I am working on implemen ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: https://i.sstatic.net/j9hBT.png I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selecti ...

What is the best way to continuously run a series of setInterval() functions in a never-ending

I attempted to create a function that would post measurement A every 5 seconds for 10 times, followed by posting measurement B at random intervals. The goal was to have this function repeat indefinitely in order to simulate a fake agent. My initial code l ...

How can scriptlets be used to dynamically create a properly functioning model?

Having trouble populating data into the modal form. I've tried placing the modal code inside a for-each loop, and while it successfully displays the details in the modal, the functionality of the close button and clicking outside the modal to close it ...