Using Axios in a Vue component to modify a user's settings

I'm currently working on updating a preference, with the UI example attached below. The default option is set to yes, but I would like to give users the choice to select no as well. I feel like I may be missing something here, so any guidance or assistance in identifying my errors would be greatly appreciated.

https://i.sstatic.net/nNcPK.png

Parent Component:

        <CommunicationPreference
          v-for="(communication, index) in communicationPreferenceType"
          :key="index + communication.name"
          :consent="communication.consent"
          :name="communication.name"
          @accept-consent="acceptConsent"
          @decline-consent="declineConsent"
        />

  methods: {
    async acceptConsent() {
      await this.$store.dispatch('account/updateCommunicationPreferences')
    },
    async declineConsent() {
      await this.$store.dispatch('account/updateCommunicationPreferences')
    },
}

CommunicationPreference.vue Component:

      <Button
        :text="Yes"
        :type="consent === true ? 'primary' : 'secondary'"
        @clicked="acceptConsent"
      />
      <Button
        :text="No"
        :type="consent !== true ? 'primary' : 'secondary'"
        @clicked="declineConsent"
      />


  methods: {
    acceptConsent(consent) {
      this.$emit('accept', consent === true)
    },
    declineConsent(consent) {
      this.$emit('decline', consent === false)
    },

Store:

 async updateCommunicationPreferences({ commit, state }) {
    const { communicationTypeName } = state.communicationTypeName

    if (!communicationTypeName) {
      return
    }

    try {
      const response = await this.$axios.put(`/communication-consent/${communicationTypeName}`)
      const { data: updatedCommunicationPreferences } = response.data

      commit('SET_UPDATED_COMMUNICATION_PREFERENCES', updatedCommunicationPreferences)
    } catch (error) {
      commit('ADD_ERROR', { id: 'updateCommunicationPreferences', error }, { root: true })
    }
  },

Answer №1

It was pointed out in the comments that there is an error in the method name being called. According to @qimolin, the values associated with each option are not being properly passed to the function responsible for saving them. This can be resolved by passing the required value when invoking the action.

methods: {
    async acceptConsent() {
      await this.$store.dispatch('account/updateCommunicationPreferences', { consent: true })
    },
    async declineConsent() {
      await this.$store.dispatch('account/updateCommunicationPreferences', { consent: false })
    }

Alternatively, a more streamlined approach could involve using a single method:

<CommunicationPreference
          v-for="(communication, index) in communicationPreferenceType"
          :key="index + communication.name"
          :consent="communication.consent"
          :name="communication.name"
          @accept-consent="acceptConsent(true)"
          @decline-consent="declineConsent(false)"
        />
methods: {
  async updateConsent(consent) {
      await this.$store.dispatch('account/updateCommunicationPreferences', { consent })
    }
}

The parameter must then be captured within the action:

async updateCommunicationPreferences({ commit, state }, payload) {
    const { consent } = payload // The selected value (true or false) made by the user.

    const { communicationTypeName } = state.communicationTypeName

    if (!communicationTypeName) {
      return
    }

    try {
      const response = await this.$axios.put(`/communication-consent/${communicationTypeName}`)
      const { data: updatedCommunicationPreferences } = response.data

      commit('SET_UPDATED_COMMUNICATION_PREFERENCES', updatedCommunicationPreferences)
    } catch (error) {
      commit('ADD_ERROR', { id: 'updateCommunicationPreferences', error }, { root: true })
    }
  },

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

How can one quickly display a confirmation dialog box within react-admin?

Looking for a way to implement a confirmation dialog in my react-admin project, similar to JavaScript's alert function but more visually appealing. I want the user to only proceed with certain database operations if they click OK on the dialog. I cou ...

"JavaScript's versatility shines through with its ability to handle multiple variables

Presently, I am working with the following script: <v-tab :title="siteObject.xip_infos[index].lineid" > <div class="description text-left" :class="{ 'text-danger': item.status === 'DEACTIVE' }"> <small v-for="(f ...

Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used: const firebase = require("firebase"); const http = require('http') require("firebase/firestore"); firebase.initializeApp({ apiKey: '...' ...

Remove any text in the textarea beyond the fifth line

I am looking for a way to implement a functionality where every character after the 5th line in a textarea will be automatically deleted, and the 5th line will only contain a maximum of 15 characters. Currently, I have managed to achieve this to some exte ...

Is the typeahead feature acting unusual - could this be a glitch?

My input field uses typeahead functionality like this: <input type="text" id="unit" name="unit" class="form-control form-input" ng-model="item.unit" autocomplete="off" typeahead-min-length="0" uib-typeahead="unit a ...

Refreshing the browser causes AngularJS to disregard any cookies that have been set

Building an AngularJS single-page application with SQL, Node.js, and Express that incorporates login functionality using Passport and basic authentication. Once logged in, users can access routes to edit items in the database successfully. However, there s ...

Vue app experiencing issues with .env file not displaying all characters

My .env file has the following variable defined: VUE_APP_CLIENT_SECRET=$2a$10$tgYzYgMgTsdfLlRFtkd9IeEc2W4v/0EuG1uf05ztQARqhsf3esr9D5Zi When I try to access this variable using process.env.VUE_APP_CLIENT_ID, it only returns "/0EuG1uf05ztQARqhsf3esr9D5 ...

Learn how to effortlessly download a file from Amazon S3 using Angular and ng-click technology

When attempting to download a file from my Amazon S3 bucket using Angular's ng-click, I am receiving a blank file instead of the expected content. HTML <div class="details-field"> RC Book <font class="digit" >({{rcCount}})</font> ...

Issue: unable to establish a connection to [localhost:27017]

Upon executing node app.js, an error message is displayed: Failed to load c++ bson extension, using pure JS version Express server listening on port 3000 events.js:85 throw er; // Unhandled 'error' event ^ Error: failed to conn ...

Adjust the margin-top of the navigation bar with animation upon clicking the button

I have implemented a Cookie bar that is fixed at the top of my website. When the Close icon is clicked, the bar fades away. Due to the positioning of the div, I am also pushing down my .nav element by 64px. Inquiry: Is it feasible for the margin-top on ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

Performing a cross-domain JSON Get request with JQuery

Struggling with a simple JSON get request to an API on a domain that I don't have control over. Here's the code I'm using: $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://pu ...

Encountering issues with app functionality following update to Ionic RC4 version

Since upgrading from Ionic rc3 to rc4, I've been facing difficulties running my app smoothly. The app compiles without any errors when I use ionic-app-scripts build --prod, but when I try to run it on my iPhone, all I get is a blank screen and an err ...

Sweetalert is currently experiencing issues with its service functionality

I've searched around but can't find a clear solution to my issue. I need help with implementing sweetalert function in my component, specifically for data deletion using the service. https://i.sstatic.net/o6W2n.png Component Swal({ title: ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

"Encountering issues with $http.get() function in my controller while trying to

Currently, I am working on an Application that utilizes Angularjs. I am trying to call an API and retrieve data using $http.get(). However, I am facing an issue where my API url does not seem to work properly. Interestingly, when I use a URL from a tutoria ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...

Revamp webpage content and links without refreshing the page, similar to the navigation menu on Facebook

My website consists of two HTML pages, specifically contact.html and index.html. Additionally, there is a menu-sidebar and a content div integrated into the web design. There are two main objectives I am looking to achieve: 1. The ability to swap between ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...

Guide to utilizing the importcss plugin in TinyMCE Version 4.0.10: Troubleshooting content_css loading issue and resolving style dropdown display problem

We are currently using the latest version of TinyMCE, specifically v 4.0.10 Our goal is to load content_css and have a dropdown of styles available in the styleselect menu. According to TinyMCE 4.x documentation, we attempted to achieve this by incorpora ...