How to trigger a dispatch action in Nuxt.js store to update the state

After reading some articles on the topic, I am still struggling to understand it completely.

This is my current issue:

I have a component in Nuxt

<a @click="openMenu">Open Menu</a>
<div v-if="isUserNav"> ...  </div>

Essentially, I want to change the state of `isUserNav` to true when clicked by using Vuex store.

In my component, I have access to the state:

import {
mapState
} from ‘vuex’

export default {
    computed: {
        ...mapState({
            isUserNav: state => state.isUserNav
        })
    },
    methods: {
        openMenu () {
            this.$store.commit('openMenu')
        },
    }
}

Here is the Vuex store configuration:

import Vuex from 'vuex'

const createStore = () => {
    return new Vuex.Store({
        state: () => ({
            // USER NAV COMPONENT
            isUserNav: false,
            testData: "Hello"
        }),
        actions: {
            async openMenu() {
              this.state.isUserNav = true;
            }
          }
    })
}

export default createStore

I seem to be encountering an error where I can't run the action as intended. Even though I can access the action, it is throwing:

[vuex] unknown mutation type: openMenu

error in console.

Where did I go wrong and what steps do I need to take next?

Answer №1

The error you made can be pinpointed to:

this.$store.commit('openMenu')

This line triggers a mutation instead of an action. Since the mutation 'openMenu' does not exist, you are receiving the error message

[vuex] unknown mutation type: openMenu
.

To trigger an action correctly, you must use this.$store.dispatch('openMenu').

However, it seems like your action is incorrectly written and actions should not directly mutate the state. They should commit mutations which will then update the state.

Resolution

In this case, switching your action to a mutation may be sufficient in achieving your desired outcome.

mutations: {
  openMenu(state) {
    state.isUserNav = true
  }
}

For more information on mutations and actions, refer to the vuex documentation:

These resources provide a thorough explanation of both concepts and their respective use cases.

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

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Vue Router hit a snag: the call stack size has been surpassed

I've been trying to check if my jwt token is expired or not in my route guard. Somehow, I'm stuck in an infinite loop and can't figure out why. Here's the snippet of my code: Route Guard const parseJwt = (token) => { const base6 ...

Issue with Vue directive bind not functioning after element refresh

My approach involves utilizing vue.js to create forms, where all fields are structured within a JavaScript objects array. Here is an example of the structure I use: { type: "input", mask: "date", default: "2018/04/14" }, { type: "input", ...

Utilizing Vuex to implement a search functionality in a list

I've encountered an issue with my vueJs application. I have a list of uploaders and a search bar, but after incorporating vuex, the list is no longer rendered. Following the guidance provided in this question, I implemented the following: <templat ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

What could be preventing me from updating data using a Vuex module?

Hello, this is my custom component code: methods:{ ...mapActions(['updateUsers']), Update(userID){ let formData = new FormData(); formData.append('new_name',this.editUser.new_name); ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

The FontLoader feature seems to be causing issues when integrated with Vuejs

While working on a Vue project with threejs, I encountered an error similar to the one described here. The issue arose when attempting to generate a text geometry despite confirming that the path to the typeface font is accurate and in json format. ...

Populating and dynamically sorting a v-select component in Vuetify

I am working on populating and sorting an array dynamically for use in a v-select component. However, I am encountering the es-lint warning 'unexpected side-effect in computed property' because I am modifying objects within that function call. Is ...

Incorporating an external Angular.js library into a Vue.js Single File Component

I am working with a Single File Component in Vue.js that includes the following code. The plasmid tag should be rendered by the angularplasmid.complete.min.js file, but it doesn't seem to be working. I'm wondering if this is the correct way to i ...

What are the steps to integrating a chat feature into my web application using Vue and Java EE?

I have developed a Web Application using Vue.js, REST(JSON), and Java EE with Payara Server as the backend. Now I am looking to integrate a chat feature into my application. The chat should include fixed chat rooms (global, groups) as well as private user ...

Establish a Vue application to run on Nginx at port 80 in Raspbian, paired with a Flask backend operating on port 8080

My setup involves Nginx running a Flask-based backend on port 8080 with the following configuration: server { listen 8080 default_server; listen [::]:8080; root /var/www/html; server_name _; location /static { alias /var/www ...

vuejs props become null upon page refresh

MyComponent.vue template: <ResponsiveNavigation :nav-links="navLinks" /> script data: () => ({ navLinks: [] }), created: function() { this.getSocialMediaLinks(); }, methods: { getSocialMediaLinks() { var self = this; ...

Clicking on a button will trigger the opening of a modal dialog

I encountered an issue with the following code: <sepa-modal ref="sepaModal" /> <b-card id="show-btn" class="card-modal" @click="openSepaModal()" > </b-card> openSepaModal ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

Is it possible to preserve the query parameters from the previous page using Vue Router's Navigation guard feature?

Hey there! So, I'm looking to pass a query from the current page to the next one without manually coding it into all of my push functions. I was wondering if there's a way to do this through Navigation guard or some hooks? I did some research an ...

Error TS2304: Unable to locate identifier 'RTCErrorEvent'

I am currently working on a WebRTC application using Quasar, typescript and Vue. In my code snippet below, I am encountering an issue where I don't get any errors in WebStorm (as it uses the project's eslint config), and I can navigate to the def ...