I keep encountering a Vuex error stating ReferenceError is not defined. What is the correct way to properly set a value

I have a question regarding Vuex. How can I properly set a value for signupError in my function signUp()?

I attempted using the following code snippets: commit(signupError, null) and

$state.commit(signupError, null) 
, but I encountered an error stating "ReferenceError: signupError is not defined".

Could you provide guidance on how to correctly set up signupError in the given scenario?

store.js

import Vuex from "vuex";
import Vue from "vue";
import { Auth } from "aws-amplify";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
    signupError: null
  },


  actions: {
    async signUp({ commit }, { username, password, firstName, lastName }) {
      commit(signupError, null)
      try {
        const data = await Auth.signUp({
          username,
          password,
          attributes: {
            email: username
          }
        });
       
      } catch (error) {
        state.signupError = err.message || err
        console.log('error signing up:', error);
        return error;
    }

main.js

....

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store: store, // Vuex mechanism to "inject" the store into all child components from the root component.
  render: h => h(App),
  router
})

reg.vue

....
 await this.$store.dispatch('signUp', {....

Answer №1

You have a missing mutation, as a call to commit requires a mutation for it to commit.

mutations: {
  SET_ERROR(state, value) {
    state.signupError = value;
  }
}

Ensure that when you call commit, you pass the mutation name and payload:

commit('SET_ERROR', null);

Remember to include this in the catch block because you can't directly set state from an action:

commit('SET_ERROR', error.message || error);

Be consistent with your variable names; choose either err or error and stick with it throughout your code

The complete action should look like this:

actions: {
  async signUp({ commit }, { username, password, firstName, lastName }) {
    commit('SET_ERROR', null);
    try {
      const data = await Auth.signUp({
        username,
        password,
        attributes: {
          email: username
        }
      });
    } catch (error) {
      commit('SET_ERROR', error.message || error);
      console.log('error signing up:', error);
      return error;
    }
  }
}

In addition, ensure you are handling the data returned by the asynchronous call appropriately.

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

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

What could be causing the shadow to appear misplaced in Three.js?

I have a blue car and a yellow sphere on top. The source of light is coming from above. Why does the shadow appear in the wrong spot? Code: http://jsfiddle.net/kLmn9/ Edit: When I adjust the light.shadowBias, the shadow on the ground becomes accurate, b ...

I attempted to retrieve a PHP file in my HTML document using AJAX, however, the scripts embedded in the file are not functioning as expected

I have successfully integrated a php file into my HTML document using AJAX. However, I am encountering an issue with the script tags within the PHP file. These scripts work perfectly when the PHP file is viewed individually, but when called using AJAX, the ...

In what ways can I apply the outcome of this commitment?

I need help refining the buildQuery function for my social post feed: const buildQuery = (criteria) => { const { userId, interest } = criteria; const query = {}; if (interest !== 'everything') { if (interest === 'myInterests&a ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

Does anyone have tips on how to upload images to MongoDB using React?

Currently, I am working on a project that requires an image upload feature for users. These images need to be stored in MongoDB so that they can be viewed by the user later on. Can anyone offer assistance with this? I have successfully configured my datab ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

Implement a delay for updating the style of a button by using the setTimeout function

Is it possible to create a button that, when clicked, changes color to green and then reverts back to its original style after 3 seconds? I am able to change the button color using an onClick event in my script. However, I encounter scope errors when tryi ...

Adjust the border hue of the MUI disabled outline input

I am currently struggling to locate the exact definition of this border color. After inspecting the dom, I cannot seem to find any border style within the input component or its pseudo elements... My main goal is to slightly lighten the color of the input ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

Using multiple images to create a visual in three.js

Looking to create a unique shape or maybe even a word using three.js by incorporating various pictures. Take, for example, the following image: https://i.sstatic.net/9O1dF.jpg My plan is to determine the points that will form the desired shape and then p ...

Issue with react-intl not updating the placeholder value

Is there an error in my implementation? I have utilized the intl.formatMessage() API (https://github.com/yahoo/react-intl/wiki/API#formatmessage) in this manner: this.intl.formatMessage({id:'downloadRequest.success',values:{correlID:'test& ...

Disabling the previous and next buttons in an MD tab

I'm dealing with an issue involving my angular material tab. Here is the code snippet: <md-tabs md-dynamic-height md-border-bottom md-stretch-tabs="never" md-no-bar md-no-ink id="tabcontainer" md-selected="tabdata.selectedIndex" md-no-ink class="m ...

What are the best methods for improving the rendering performance of multiple sphereGeometry objects in three.js?

Looking to improve the rendering performance of sphereGeometry in my three.js program, as it is currently a bottleneck. Here is the JavaScript code I am using: var sphereThree = []; for(var idSphere = 0; idSphere < numSphere; idSphere++){ var spher ...

Adjusting the speed of Vuetify transitions: A guide on setting the perfect transition speed

Looking to have an audio player component smoothly slide up from the bottom of its parent component? You can nest it within a <v-slide-y-transition> Vuetify component, but how can you control the speed of the sliding animation? <v-parallax src= ...

Tips for initiating a function at a designated scroll point on a webpage

Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...

Securing routes in Node.js using Passport.js

Within my express app, the main server code is contained in the server.js file. In this file, there is a route defined as app.get('/dashboard',require('./dashboard/dashboard.js'). The dashboard.js file contains multiple routes such as ...

I'm struggling with a namespace conflict in Javascript - how can I access this value in the function call?

Having a bit of trouble figuring out how to obtain the desired value within this function. Any ideas? Thanks! temp = exotics[i].split(','); if ($.inArray(temp[0], tblProbables) != -1) { item = $("<li><a id='" + temp[0] + "&apo ...