create a new Vuex.Store and include Mutations

Having trouble using the commit method as described here. I suspect it's because I'm using export default new Vuex.Store instead of

export const store = new Vuex.Store
. However, when I make this change, I encounter an issue similar to the one in this post.

You can find my JS file where I'm utilizing Vuex and trying to use commit here:

actions: {
  signUserIn(payload) {
    payload.password;
    var params = new URLSearchParams();
    params.append("grant_type", "password");
    params.append("username", "admin");
    params.append("password", "adminPassword");
    axios({
      method: "post",
      url: "http://localhost:8090/oauth/token",
      auth: { username: "my-trusted-client", password: "secret" },
      headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
      },
      data: params
    }).then(function(response) {
      const user = {
        login: payload.username
      };
      localStorage.setItem("access_token", response.data.access_token);
      this.commit("setUser", user);
    });
  }
},

When attempting to run this code and call signUserIn, I receive the following error in the console:

TypeError: Cannot read property 'commmit' of undefined

I'm not sure what keywords to search for to resolve this issue.

Answer №1

It seems like there may have been a typo. The correct syntax should be commit instead of commmit.

UPDATE: After reviewing the file, I suggest using arrow functions for better efficiency.

axios({
    method: "post",
    url: "http://localhost:8090/oauth/token",
    auth: { username: "my-trusted-client", password: "secret" },
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
    },
    data: params
  }).then(response => {
    const user = {
      login: payload.username
    };
    localStorage.setItem("access_token", response.data.access_token);
    this.commit("setUser", user);
  });

The reason for using arrow functions is to maintain the context of this. Using arrow functions ensures that this remains consistent with the outer context. It's worth experimenting both with and without `this` in your specific scenario. (I might have mentioned 'this' quite a lot)

Answer №2

Your action method needs to be updated with the correct signature. Take a look at the Vuex documentation, which specifies that the action method should take the Vuex context as the first parameter and the payload as the second:

// signUserIn(payload) { // DON'T DO THIS
signUserIn(context, payload) {

If you stick with your current code, you'll find that both payload.username and payload.password are undefined.

Check out this demo showcasing the bug in your action.

To resolve this issue, update your action method to resemble the following structure:

actions: {
  signUserIn(context, payload) {
    axios.post().then(response => {
      context.commit('foo', foo);
    });
  }
}

Here's a demo demonstrating the fix.

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

Send a troublesome string from the client to the server and receive the identical string in return

Having trouble sending the game record from my client to my server: [Event "fics server game, rated blitz match"] [Site "Internet Chess Server: freechess.org 5000"] [Date "1999.11.07"] [Time "06:26:??"] [Round " ...

The slow loading time of the website can be attributed to the excessive loading time of over 30 seconds due

My website, , is experiencing slow loading times due to a file named "json.gdn/gpl" which is causing it to take over 30 seconds to load completely. Unfortunately, I am not familiar with how to resolve this issue. I discovered this problem while using . If ...

Eliminate the listener if the connected function contains a binding

Here is a code snippet to consider: class Test { constructor() { this.breakpoints = {}; } add(options) { // Register the media query this.breakpoints[options.breakpoint] = window.matchMedia(options.breakpoint); ...

What is the best way to pass data from a parent component to a child component and utilize it within a function in Next.js

As a beginner in react and nextjs, I am struggling with passing the "response" from a function in the parent component to another component (component1). function func1(props) { function handleSubmit(e) { e.preventDefault(); v ...

Integrating Mailchimp with MongoDB and Node.js

As of now, I am managing a database of users in MongoDB and my goal is to provide them with regular updates on new content available on a real-estate marketplace website on a daily basis. My plan is to send out email notifications to each user every day w ...

Executing JavaScript when a specific portion of a webpage loads in the presence of AJAX: A guide

As I tackle a project that involves loading elements via AJAX within a CMS-type software, I find myself restricted in accessing the AJAX code and its callbacks. One specific challenge I face is running my function only when a certain part of the page is l ...

Preflight request denied due to access control failure. No 'Access-Control-Allow-Origin' header present

I am currently working on a Vue.js application that utilizes axios to send requests to an ApiGee Server. Below is the code snippet I am using to send requests to APIgee. const headers = { 'X-API-Key': 'randomKey123123' } ...

Retrieve and update the most recent entry

Here is the schema I am working with: var BudgetInfoSchema = mongoose.Schema({ user_email: { type: String, required: true }, user_budget: { type: Number, required: true }, platforms_budget: { type: [{ platform_id: { type: String, required ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...

Error encountered in Angular JS: $parse:syntax Syntax Error detected

var app=angular.module('myapp',[]) app.controller('myctrl',Myfunction); function Myfunction($scope,$compile){ var self=this; $scope.text=s4(); $scope.adding=function(){ var divElement = angular.element($("#exampleId")); ...

Struggling with uploading a Vue project to Github Pages

I attempted to deploy my vue-cli project on Github Pages by following the guidelines provided on a website and on GitHub's support page. To deploy vue-cli to Github Pages, refer to this link: https://medium.com/@mwolfhoffman/deploying-to-github-pages ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

Tips for creating a fixed footer that adjusts with a flexible wrapper

Feeling incredibly stressed, I embarked on a quest to find the perfect sticky footer. After searching Google for what seemed like an eternity, I came across multiple tutorials recommending the use of min-height:100%. However, this approach caused the wrap ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

The function to save a mongoose schema is not valid

I encountered an issue with the StripeToken.save function while using the code snippet below. After double-checking my model, I can't seem to pinpoint what went wrong. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var s ...

beforeprinting() and afterprinting() function counterparts for non-IE browsers

Is there a way to send information back to my database when a user prints a specific webpage, without relying on browser-specific functions like onbeforeprint() and onafterprint()? I'm open to using any combination of technologies (PHP, MySQL, JavaScr ...

Vuetify Error - "Attempting to access 'extend' property of an undefined object"

Upon installing Vuetify, I encountered an error in the console. My webpack version is v3.6 Uncaught TypeError: Cannot read property 'extend' of undefined at Module../src/mixins/themeable/index.ts (index.ts:21) at __webpack_require__ (boo ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...