The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) ReferenceError: dispatch is not defined' when attempting to call an action from another action using the dispatch key in auth.js.

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import auth from './auth'

Vue.use(Vuex);

export default new Vuex.Store({
    state: {},
    mutations: {},
    actions: {},
    modules: {
        auth
    }
})

auth.js

import axios from "axios";

export default {
    namespaced: true,
    state: {
        token: null,
        user: null
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token;
        },
        SET_USER(state, data) {
            state.user = data;
        }
    },
    actions: {
        async signIn(_, credentials) {
            let response = await axios.post("auth/signin", credentials)
            /* eslint-disable */
            dispatch('attempt', response.data.token);
        },
        async attempt({commit}, token) {
            commit("SET_TOKEN", token);

            try {
                let response = await axios.get('auth/me', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                commit("SET_USER", response.data)
            } catch (e) {
                commit("SET_TOKEN", null);
                commit("SET_USER", null);
            }
        }
    }
}

SignIn.vue

<template>
    <div>
        <form @submit.prevent="submit">
            <div>
                <label for="email">Email</label>
                <input id="email" type="email" name="email" v-model="form.email">
            </div>
            <div>
                <label for="password">Password</label>
                <input id="password" type="password" name="password" v-model="form.password">
            </div>
            <div>
                <button type="submit">Submit</button>
            </div>
        </form>
    </div>
</template>

<script>
    import {mapActions} from "vuex";

    export default {
        name: "signIn",
        data() {
            return {
                form: {
                    email: "",
                    password: ""
                }
            }
        },
        methods: {
            ...mapActions({
                signIn: 'auth/signIn'
            }),
            submit() {
                this.signIn(this.form)
            }
        }
    }
</script>

Answer №1

When attempting to use async in the signIn() function, make sure to include {dispatch} in the parameters as shown below: async attempt({dispatch}, token)

Fingers crossed that this solution will work!

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

Unable to locate node module when using Npm.require

I've been attempting to utilize the Npm.require method in order to access the ldapjs module for client authentication. Unfortunately, I'm encountering the following error message: var ldap = Npm.require('ldapjs'); Error: Cannot find ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

Displaying the chosen option from the V-menu in a different section of the application. Utilizing Vuetify

I'm working with a v-menu that has multiple options. I want to be able to display the selected option in another section of my application within the same component. Even though I attempted to use v-model for this purpose, it doesn't seem to work ...

Eliminate error class in jQuery Validate once validation is successful

I'm having an issue with the jQuery Validate plugin. Even after a field is successfully validated, the "error-message box" continues to be displayed. How can I remove this box? Here's my code: CSS: .register-box .field .has-error{ border ...

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

What is the process of implementing a service in AngularJS?

For my Angular JS project, I am working on creating a module to include my service (file: utils/productos.js) and then load it as a dependency for my ventas module (ventas/ventas.js). However, I encountered the following error: Error: [$injector:nomod] Mo ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

What is the process of converting PUG to JSX?

I am currently attempting to integrate Pug code within a JS react application. While researching, I came across this plugin here, which can assist in converting the code. However, it seems to have an issue with handling the "." statements present in the c ...

Utilizing JavaScript to trigger the :hover pseudo-class and implement event transfers

Consider this situation: You have a scenario where two images are stacked on top of each other. The image with the highest z-index is transparent and handles click events, similar to Google's Map API, while the image below is for visual representatio ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

What is the proper way to safely close the pg-promise connection in a node.js environment once all jest tests are completed?

I am facing a challenge in closing a PG-Promise database connection after running a function test in Jest. The database connection is initialized in one central location (db.js) and required in multiple places. In this scenario, it is being used by seed.j ...

Declarations and expressions in Node.js using JavaScript

Recently diving into Node Js, I stumbled upon the following code snippet in a tutorial const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const questions = [ " ...

What are the steps for generating and implementing shared feature files in Cucumber?

I am currently utilizing Cucumber to define some tests for the project I am working on, but as the application grows larger, I find myself in need of a more efficient structure. project | feature_files | | app1.js | | app2.js | | app3.js ...

What is the best way to conceal an image tag depending on an ajax response?

What is the correct jQuery statement to replace the "//Needed incantation" comments below so that the image tags are displayed or hidden based on the AJAX responses? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application: webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script& ...

Run JavaScript upon the webpage loading without the dependency of jQuery

Is there a way to ensure that JavaScript code is executed only after the entire page has loaded, without relying on jQuery? Take this example... <html> <head> <script type="text/javascript"> var box = document.ge ...

Combining numerous data tables in Vue.js directly from JSON information through a single template

I need to develop a single vue template to display over 40 datatables with different table definitions passed in through an API. I am facing a challenge in dynamically pulling in the table data using key names defined in the table settings. I attempted t ...

Ways to show text on a donut chart when hovering with the mouse

I have been attempting to make adjustments to this sample. My goal is to display a word in the center of the donut chart upon mouseover, similar to this: https://i.sstatic.net/dCPKP.png Although I have included code for mouseover, it seems to not be func ...

What is returned by jQuery when it fails to locate a specified class selector within the jQuery object?

Picture this scenario: var $letsTestA = $( '.lets-test-a' ), $letsTestB = $( '.lets-test-b' ); Then, consider this HTML: <div class="lets-test-a"></div> (I omitted .lets-test-b intentionally) Now, what happens if we ...