Ways to update vuex state using mutations

Currently, I am facing an issue while working on an app where I'm attempting to change the Vuex state using mutations but it's not functioning as expected. Initially, the state.status is set as an empty string, and my goal is to update it to the value of the variable token, which is also a string. I have implemented the updateToken mutation for this purpose. Despite trying methods like Vue.set(state, 'status', token);, I keep encountering errors (specifically:

"Cannot read property 'set' of undefined"
). Even after passing the token to the second mutation, it remains empty, although the console.log() displays the correct token.

Below is a snippet of my code from store.js:

import { createStore } from 'vuex';
import axios from "axios"

const msgFormData = new FormData();

const store = createStore({
    state: {
        status: "",
    },
    mutations: {
        updateToken(state, token) {
            state.status = token
        },
        sendToken(state, user_name) {
            msgFormData.set('user_name', user_name);
            msgFormData.append('msg_token', state.status);

            axios.post("http://someip/index.php", msgFormData)
            .then(res => {
                console.log(res.status)
            })
            .catch(error => {
            console.log(error)
            })
        },
    }
});

export default store;

I make calls to these mutations like this:

this.$store.commit('updateToken', token.value)
in a Vue file and
this.$store.commit('sendToken', this.user.email)
in App.vue.

If anyone can provide guidance on what mistake I might be making, I would greatly appreciate it.

Answer №1

  • Consider using an action instead of a mutation when dealing with asynchronous tasks, such as the sendToken operation
  • For better functionality, ensure that
    const msgFormData = new FormData();
    is placed within the sendToken method to generate a fresh instance of FormData every time the method is called

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

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

Tips on inserting text into form input fields

I need some guidance on how to enhance my form input functionality. The form currently consists of an input box and a submit button. When the user clicks submit, the form content is submitted and processed using javascript. What I am aiming for is to autom ...

What is the best approach to create a dynamic value from axios response in a reactive object?

I am attempting to retrieve data from the backend (specifically the user role) and store it in a reactive container with Vue: import {reactive} from "vue"; import axios from "axios"; export const store = reactive({ auth: axios.get ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

I'm trying to implement a command in my bot that displays the number of Discord members, but I keep encountering an error

I've encountered an issue with the discord.js v13 member count command. Despite seeking help in various Discord servers, I haven't received any assistance. If anyone could offer their expertise, it would be greatly appreciated. const Discord = re ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

implement a dropdown feature for a vertical menu with the help of Jquery

Struggling to implement a dropdown feature on a vertical navigation using Jquery. The HTML includes a nav section with 1st level list items and nested li's for second level menu items. On clicking the 1st level li, the intention is to toggle SHOW/HID ...

Issue with Vue template not displaying within a loop

After completing a basic Vue tutorial on setting up a Todo app, I decided to integrate some aspects of it into a website I am developing. However, I have encountered an issue with my for-loop that is not functioning as expected. The project was initially ...

Discover the steps to traverse through directories and their numerous subdirectories (including a whopping 15000 subdirectories) with the help of the directory-tree

We are currently utilizing the directory-tree npm package to access and read through all directories and subdirectories, noting that there are as many as 15000 nested subdirectories. Code snippet in use: const dirTree = require("directory-tree"); const ...

Oops! The program encountered an error where it cannot assign a value to the 'id' property of an undefined object while trying to store a session in redis

I am currently working on an Angular4 login application and I am looking to store sessions in Redis. To accomplish this, I am utilizing Express session. However, I have encountered the following error: req.session.id = userName; ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

How to effectively transfer a JSON object from a Python function to JavaScript using Eel, allowing you to seamlessly utilize and modify the JSON data

Let's delve into a slightly confusing question together. Have you heard of Eel? It's a Python module that lets you use functions created in Python in Javascript, and vice versa. What I want to achieve is taking a JSON object generated by a Python ...

Utilize a MongoDB query to locate a single document and include a conditional statement within the update operation

I've been struggling with this problem for quite some time now and I could really use some guidance from experts here on SO. Essentially, what I am trying to achieve is to locate a specific document using a provided _id, and then execute a conditional ...

Is there a way to solely adjust the color of a -box-shadow using jquery?

Looking for a way to incorporate tinycolor, a color manipulation framework, into setting a box-shadow color. Instead of directly setting the box-shadow with jQuery, you can use tinycolor on an existing color variable. $("CLASS").css("box-shadow", "VALUE") ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Need to know how to retrieve the li element in a ul that does not have an index of 2? I am aware of how to obtain the index greater than or less

I'm looking to hide all the li elements except for the one with a specific index. I've written some code to achieve this, but I'm wondering if there's a simpler way using jQuery. While jQuery provides methods like eq, gt, and lt, there ...

Certain crucial happenings inhibit the ability of others to occur

Hey there! Want to check out the live application I'm currently working on? Simply click this link: turbo_synth This project is being developed using VueJS, however, the issue I've encountered does not seem to be related to Vue at all. The prob ...

Adjust the background of the input range style prior to the thumb icon

Is there a way to style the bar before the thumb with a different color on a range input? I have been searching for a solution without much success. This is the desired look: Unfortunately, Chrome no longer supports input[type='range']::-webkit- ...