"Encountering an issue where a Vuex action is unable to retrieve the property's

I am facing an issue with passing data to my Vuex action. Each time I try, I encounter the error message

TypeError: can't access property x, data is undefined
. Despite trying different approaches to pass the property value, I have been unsuccessful. Could you please review my code and point out where I might be going wrong?

Store:

import axios from 'axios'

export default {
  namespaced: true,
  state: {
    announcements: []
  },
  getters: {},
  actions: {
    createAnnouncement({ commit }, courseId, data) {
      return new Promise((resolve, reject) => {
        axios
        .post(`teacher/courses/announcements/create/${courseId}`, { title: data.title, message: data.message })
        .then((response) => {
          commit('ADD_ANNOUNCEMENT', response.data.data)
          resolve(response)
        })
        .catch((error) => { reject(error) })
      })
    }
  },
  mutations: {
    ADD_ANNOUNCEMENT(state, newAnnouncement) {
      state.announcements.push(newAnnouncement)
    }
  }
}

Component:

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  data() {
    return {
      title: '',
      message: '',
    }
  },
  computed: {
    ...mapGetters('courses', ['getCourseData'])
  },
  methods: {
    ...mapActions('announcements', ['createAnnouncement']),
    onSubmit() {
      const { announcementTitle, announcementMessage } = this
      const courseId = this.getCourseData.id
      this.createAnnouncement(courseId, { title: announcementTitle, message: announcementMessage }) 
    }
  }
}
</script>

Answer №1

Commands will only accept two parameters, the context and an optional data payload.

Experiment with modifying your command to be

createAnnouncement({ commit }, { courseId, information }) {
  //...
}

then execute it using

const dataPayload = {
  courseId: this.getCourseInformation.id,
  information: {
    title: this.announcementTitle,
    message: this.announcementMessage
  }
}
this.createAnnouncement(dataPayload)

Refer to https://vuex.vuejs.org/api/#actions

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

Is there a regular expression that can identify whether a string is included in a numbered list?

Struggling with creating a regular expression to determine if a string is part of a numbered list like those in word processors. Need it to return true only if the string starts with a number, followed by a full stop and a space. Easy for single or doubl ...

Converting current JavaScript code into AngularJS services

Looking for a way to utilize an old JS library containing functions like the following in Angular code: function TestService() { } TestService.init = function() { ------ } TestService.foo = function() { -------------- } Is there a method to encapsulat ...

I want to know how to adjust the column placement within a row in the card group using bootstrap vue

Here is an example of my Vue component: <template> ... <b-card-group deck v-for="row in formattedClubs"> <b-card v-for="club in row" :title="club.description" img-src="http://placehold.it/130?t ...

The navigation bar created with HTML, CSS, and JS is not displaying the menu as expected and is also experiencing issues with changing the order of links

I'm currently in the process of revamping my portfolio site, opting to use Bootstrap for the layout due to its efficiency. While attempting to implement a drop-down navbar using Bootstrap, I encountered difficulties as the menu failed to appear. Thus, ...

The Jquery locator is searching in the incorrect page following a reload

I am facing an issue with loading dynamic content into a div on my website. Here's the setup: I have two pages named default.aspx and widgets/rss.aspx. On default.aspx, I use the following code to load rss.aspx into a div: $.get('/Widgets/rss. ...

One specific JS file fails to load only when using Internet Explorer Browser in conjunction with the debugger

I am encountering an issue with a project that utilizes angular JavaScript controllers to populate fields. Unfortunately, a specific page, members.cshtml, is not loading properly in Internet Explorer 11, despite working perfectly on Chrome and Firefox. Af ...

Prevent unwanted padding in lists by using CSS float inside

When organizing my list element, I want to position the control buttons next to the left of the list item text. To achieve this layout, I have applied the CSS property float: left;. However, a problem arises when there are multiple lines in a list - each n ...

Running a Redux Thunk action from within a TypeScript environment, beyond the confines of a React component

Currently, I am in the process of converting a React Native app into TypeScript. Unfortunately, I have encountered an issue with dispatching thunk actions outside of the store. Below is how my store is configured: store/index.ts import { createStore, app ...

Create a JSON object with empty values

I am working with a JavaScript date array: ["2015-09-10", "2015-09-16"] My goal is to transform this array into a JSON object with the format: { "2015-09-10": {}, "2015-09-16": {} } Does anyone know how I can achieve this transf ...

Refresh stock value in anychart without having to re-render the entire chart

I am currently experimenting with the Anychart stock candlestick chart and I must say, it is quite impressive. However, I have encountered an issue while trying to update the chart using a setInterval function. The problem is that it re-plots the entire ch ...

What is the most effective approach to handling dependencies for an AngularJs 1.x web application?

Right now, I have a bunch of script elements pointing to cdn/local files, which isn't ideal. I'm considering declaring all necessary packages using npm/yarn and serving cdn files with self-hosted fallback. Is this a good idea? Would it be bette ...

Pass a String Array to FormArray: A Complete Guide

This is my Custom Form Group: this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], variants: this.fb.array([ this.fb.group({ type: '', options: this.fb ...

Exclude the file and directory patterns from being watched with PM2: ignore folder

I need help with configuring pm2 to stop monitoring folders that have names like cache or tmp. I've tried multiple approaches in my app.json configuration file: {"apps": [{ "name": "BSTAT", "script": &q ...

React: Ever wonder why changing the state directly ends up putting the component in such a peculiar state?

Before we proceed, I want to clarify that I am aware that mutating the state is not a recommended practice. However, I am curious to explore the potential consequences of directly mutating the state. Let's consider a simple todo app that stores todo ...

Capturing Ajax Success in Rails

After extensive googling, I have been unable to find my mistake. As a beginner with JS, this may be an easy fix for someone with more experience. Working with Rails 4. I am working on a modal that contains a form and I want to perform certain actions afte ...

Tips for excluding empty strings from the total length calculation

Issue: My input fields should turn into green buttons once the correct syllables are inserted. However, the problem lies in the fact that it determines correctness based on the length of my JSON data compared to what the user inputs. Even when my array con ...

Storing and securing passwords in Node/Express using hashing and salting techniques

Utilizing the Crypto module within Node's standard library is a necessity. I have established a POST route dedicated to handling a registration form: app.post('/superadmin/add-account', function(req, res) { // Creating shorthand variable ...

storing HTML elements in Chrome's cache

I have developed a content uploading module that utilizes the file API. The HTML code is <input type="file" id="filepicker-input" multiple="true" style="display:none;"/> <div class="addfile_btndiv" id="addfile_btndiv"> ...

Passing arrays to a Vue component in a static manner

I am trying to pass an array statically to my Vue component named ajax-table. After struggling to find a solution, I decided to use the following approach: <ajax-table header-names="Code, Name, Description, Type" field-names="code, name, descri ...

Having difficulty accessing the attributes of an object within a property

I am encountering an issue when trying to access the properties of an object that contains a reference property of another object. Essentially, there is an object nested within another object. Upon fetching data from API calls like this one for instance:, ...