Issues have been identified with the capabilities of Vue's Mutations and Actions

My Index.js from the Store Folder

import Vue from "vue";
import Vuex from "vuex";

import state from "../store/state";
import mutations from "../store/mutations";
import actions from "../store/actions";

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  mutations,
  actions,
});

The State.js File

/* eslint-disable */
import cats from "../data/cats.js";
import dogs from "../data/dogs.js";

export default {
  cats,
  dogs,
};

Actions.js Content

// method add pet -> dispatch action -> mutate -> state changes
export default {
  addPet: ({ commit }, payload) => {
    console.log("payload is", payload);
    commit("appendPet", payload);
  },
};

The Mutations.js Script

export default {
  appendPet: (state, { specie, pet }) => {
    console.log("specie and pet are", specie, pet);
    state[specie].append(pet);
  },
};

The Code in Home.vue


<template>
  <div class="home">
    <h1>Adopt a New Best Friend</h1>
    <button @click="formShow" class="btn btn-primary">Add New Pet</button>

    <b-form @submit.prevent="handleSubmit" v-if="showForm === true">
      <b-form-group id="input-group-2" label="Pet's Name:" label-for="input-2">
        <b-form-input
          id="input-2"
          v-model="formData.name"
          type="text"
          placeholder="Enter name"
          required
        ></b-form-input>
      </b-form-group>

      <b-form-group id="input-group-3" label="Specie:" label-for="input-3">
        <b-form-select
          id="input-3"
          v-model="formData.specie"
          :options="['cats', 'dogs']"
          required
        ></b-form-select>
      </b-form-group>
      <b-form-group id="input-group-2" label="Pet's Age:" label-for="input-2">
        <b-form-input
          id="input-2"
          v-model="formData.age"
          type="number"
          placeholder="Enter Age"
          required
        ></b-form-input>
      </b-form-group>

      <b-button type="submit" variant="primary">Submit</b-button>
      <b-button type="reset" variant="danger">Reset</b-button>
    </b-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";
export default {
  name: "Home",

  data() {
    return {
      showForm: false,
      formData: {
        age: 0,
        specie: null,
        name: "",
      },
    };
  },
  methods: {
    ...mapActions["appendPet"],
    formShow() {
      this.showForm = !this.showForm;
    },

     // mapActions and appendPet do not show on console
    handleSubmit() {
      console.log("hello this is the handle submit method");
      const { specie, age, name } = this.formData;
      console.log("specie , age and name are", specie, age, name);
      const payload = { specie, pet: { name, age } };
      this.appendPet(payload);
    },
  },
};
</script>

I am experiencing issues with my home.vue. The template section works fine, but I'm unable to mutate the state as expected. When checking the console for mapActions, it does not show any output. This leads me to believe that the appendPet method responsible for mutating the state is not being called correctly, preventing the payload from reaching the Action.js. The issue might lie with the execution of mapActions while trying to call appendPet.

Answer №1

mapActions is a special type of function that you need to use properly:

In your code, it should be like this:

...mapActions(["appendPet"])
, not
...mapActions["appendPet"]

Refer to the documentation for more details.

Answer №2

The utilization of mapActions on the mutate function is evident in your code.

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

Script designed to track modifications on a specific webpage

Attempting to purchase items online has become a frustrating challenge as stock seems to disappear within minutes of being added :/ I am currently working on creating a custom grease/tampermonkey script to monitor the page and notify me when products beco ...

Encountered an issue running "npm install" within the Vue3 composition API

Encountering an error while trying to install dependencies in a Vue3 project. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Exploring Array deconstruction and rearrangement in ES6 and React applications

My goal was to reorganize an array within my React container using a destructuring solution, which seemed like a simple task. Here is the initial array: a1 = ['hello', 'hi', 'hola'] componentDidMount() { const { a1 } = this ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Retrieve combination values through an AJAX request using ExtJS

My UI is developed using ExtJS, and I have a specific set of tasks that need to be executed when the page loads: Initiate an ajax call to the server to fetch a HashMap. Create a combobox within the main Panel on the page. var combo = Ext.create(' ...

The 'fetch' operation could not be completed on the current window due to a TypeError

The error message I am receiving is: TypeError: Failed to execute 'fetch' on 'Window' : The provided value is not of type '(sequence<sequence> or record<ByteString, ByteString>)'. My current challenge involves fetc ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

Difficulty commencing a background operation in a node.js application

I have a setup using node.js/express and React for the client side code. This setup allows users to query any number of players by making fetch requests to my express server, which then sends requests to Riot Games public API. The issue I'm encounteri ...

Converting SVG to PNG image directly in the browser (compatible with all browsers, including Internet Explorer)

I am currently working with Highcharts and I have a need to convert all the charts displayed on the webpage into images so that I can send them to my server for merging with a master export Excel file. The Excel file already contains some tables and pivot ...

JQuery restricts input to only allow numbers with a set number of digits, ensuring uniqueness

Can someone assist me in creating a jQuery script that only allows unique numbers with exactly 4 digits in a numeric field? Here is the HTML code: <input type="text" id="registration_number" class="input-sm" name="registration_number" maxlength="6" re ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

Set up a Pinia store with a specific data type

Note: I am a beginner in JavaScript I am currently working on synchronizing an object with a Pinia store and a Python REST API. My goal is to define a type just once without having to duplicate it in the store. export const useTicketStore = defineStore(&a ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

Images are no longer accessible from the public directory once a certain route is reached

My app has default layouts (footer and header) set for all pages: page.default.layout = name.startsWith("Dashboard/") ? undefined : MainLayout; The footer uses an image from the public directory, public/images/ <img src="images/payment.png" class="img- ...

The 'import' statement is not functioning properly within a script in the rendered HTML

While working on an express application, I've encountered a recurring error that I can't seem to solve. The error message is: "GET http://localhost:3000/javascript/module2 net::ERR_ABORTED 404 (Not Found)" Could someone kindly assist me in ident ...

React Server Component Warning: Server Functions cannot be invoked during the initial rendering stage

In my project, I have a client component named CampaignTable. This component requires a columns object to render the columns. Within the columns object, I include a server component called CampaignActions. The CampaignActions component is responsible for d ...

What could be causing this error to occur? I've already got node.js installed on my system

When I enter npm init in the Visual Studio Code - Insiders terminal, I get the following error message: npm init npm : The term 'npm' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

jQuery dropdown menu button impacts the entire webpage

I created this jQuery code to modify the drop menu elements, but it ended up affecting the entire page. How can I resolve this issue? $(".dropmenuac").on("click",function(){ $(".dropmenulist").css("opacity",& ...