Vuex - Avoid modifying the vuex store state directly, unless done within mutation handlers. Make sure any state changes are made

When I call a store action from the main layout (default.vue in Nuxt.js), and then call a state mutation within the mutations export, I encounter an error. Can anyone help me figure out why?

The error message in console: http://prntscr.com/rwvfjf

Here is the relevant code:

Code snippet from default.vue:

created () {
  this.$store.dispatch("update_user");
  ...
}

Code snippet from store/index.js:

export const state = {
  ...
  state: null, 
}

export const actions {
  ...
  update_user({commit}) {commit("update_user")}
}

export const mutations = {
  async update_user(state) {
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    state.user = user;
  },
}

Answer №1

According to information from the documentation:

Synchronous Mutations Requirement

An essential rule to keep in mind is that mutation handler functions must be synchronous.

It appears that the order has been mixed up. Please reorganize your action and mutation as follows:

Action

export const actions = {  // <-- was missing an equals
  ...
  async update_user({ state, commit }) { // <-- state and commit needed
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    commit("update_user", user); // <-- Passing the user data to the mutation
  }
}

Mutation

export const mutations = {
  update_user(state, user) {
    state.user = user;
  },
}

Additionally, note that the async action returns data that is then passed to the mutation, where it is assigned to state. Ensure that there are no issues with this.$axios. If there are, make sure you import it correctly:

import axios from 'axios';

and utilize it like this:

if (axios.defaults.headers.common["authorization"] == undefined) {
  axios.defaults.headers.common["authorization"] = state.token
}

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

Configuring Cypress IO to integrate with dotenv in Quasar Framework

After adding the quasar-dotenv package to my Quasar framework, I encountered an issue with e2e tests not working. https://i.sstatic.net/Ed03i.png Uncaught TypeError: fs.readFileSync is not a function This error originated from the test code and not from ...

Connection Error: Unable to Resolve Host Name socketIO

the issue I am facing is as follows: GET net::ERR_NAME_NOT_RESOLVED I have implemented an environment variable named VUE_APP_BACKEND_API using vuecli3 for the ip address. In addition to Vue.js, I am also utilizing VueSocketIO. I am unsure of the source ...

What is the process for inserting additional information into a geoJson file?

In the "gj" object, I need to add new properties from the "dataToAdd" array. The current format of "gj" is as follows: const gj = { "type": "FeatureCollection", "features" : [ { "type": "Feature", "geometry": { ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

Substitute closing parenthesis within a string with a backslash and closing parenthesis

str = 'he)llo)'; wantedStr --> 'he\)llo\)'; Attempting to achieve this result, I used: var wantedStr = str.replace(')', '\\)'); Unfortunately, the output for wantedStr remains as 'he)l ...

What could be causing my Ajax success function to never fire?

My issue is that my $.ajax success function is not triggering. I simply need to execute a PHP file without passing or retrieving any values. I found an alternative method for reading values, but it cannot run because the function must be placed within th ...

Utilizing Selenium automation to navigate a website that features a custom jQuery plugin-checkbox functionality

Utilizing Selenium WebDriver along with JavaScript to automate the testing of a website that features a custom jquery plugin named "jcf" (JavaScript Custom Forms) for aesthetically pleasing forms. You can find more information about this plugin here. I am ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

Managing form submissions using Jquery and checkboxes

Whenever I submit my dynamically created form, all checkboxes briefly become selected for a split second. Does anyone have an explanation for this behavior? Is it common or is there something wrong with my code? Although the form submits correctly, it migh ...

What is the process for decrypting the data that was encrypted using node-jose?

I am currently in the process of incorporating basic JOSE encryption and decryption functionalities by utilizing node-jose. This is my code implementation (using Node 8.2.1) const { JWE } = require('node-jose'); const jose = (publicKey, privat ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

How can I ensure that the height of my dropdown menu covers the entire screen without being limited by the page height

I'm trying to adjust a dropdown menu so that it fits perfectly within the screen size, covering the entire height without showing any content beneath or below it. Currently, the menu covers the screen on some pages but scrolls and appears too large du ...

Occasionally, an AJAX request may be terminated when making multiple calls to the API

Within an application environment, a URL is being called via AJAX four times. Interestingly, on a specific page, the AJAX request gets canceled when attempting the fourth invocation. The fourth request shows "Provisional headers are shown" in its request ...

Unable to execute controller due to service call testing failure

I'm currently working on writing a code to test the service call in my controller. The goal is to unit test a specific function within the controller that makes the service call and retrieves data. While I am using local JSON for testing purposes, the ...

What could be the reason for operators like tap and map not being invoked on the inner observable when combineLatest is used?

Can you clarify why the operators tap and map of inner observable are not being called? Shouldn't combineLatest subscribe to the observables it receives in obsArr? Why are these operators not triggered by this subscription? const obsArr = []; [[1, 2 ...

Click handler fails to trigger on dynamically rendered elements through Ajax Callback, limited to Safari browser only

I'm facing an issue with getting a feature to work on Safari and iOS devices, even though it works perfectly on Firefox, Chrome, Edge, and IE. The problem arises with an input field on the page that sends user input to the server and updates the DOM ...

Open window maximizing size

URL = "window.open('../GBY/Reports/ReportViewer.aspx?ReportParams=" + ReportParams + "&ReportName=" + ReportName + " ' , '_blank');"; ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), "OPEN_WINDOW ...