Create a notification box that appears after a successful axios request

One of the functions I have is to store an expense in my application.

storeExpense(context, params){
    axios.post('api/expenses', params)
    .then( response => {
        context.dispatch('getExpenses')
    })
    .catch( error => {
        context.commit('errors', error.response.data.errors)
        //console.log(error.response.data.errors);
    })
}

When a user clicks the submit button on my component, I simply call this action using dispatch.

store(){
    this.$store.dispatch('storeExpense',this.expense)
}

Now that I want to use sweetalert for feedback, I'm unsure of how to integrate it after a successful post request with axios.

I attempted to include it within the action itself like this:

storeExpense(context, params){
    axios.post('api/expenses', params)
    .then( response => {
        context.dispatch('getExpenses')
        this.$swal(
            'Success',
            'Expense has been updated!',
            'success'
        )
    })
    .catch( error => {
        context.commit('errors', error.response.data.errors)
        //console.log(error.response.data.errors);
    })
}

But nothing happened because it's in the action file. Should I instead call it within my component like this?

this.$store.dispatch('storeExpense',this.expense)
     .then( response => {
      this.$swal(
         'Success',
         'Expense has been created!',
         'success'
)

Do you have any suggestions on how best to implement this? Thank you!

I am new to vuejs and vuex

Answer №1

One crucial point to consider is that the concept of "this" may not align with what you are expecting in the store module - the context of "this" in the store module differs from that in components. Therefore, it is necessary to adjust your approach to triggering alerts accordingly.

  1. Begin by importing Swa into your store module:

    import Swal from 'sweetalert2/dist/sweetalert2.js'

  2. When axios completes its operation, use the following code to trigger an alert:

    Swal.fire({ title: 'Error!', text: 'Do you want to continue', type: 'error', confirmButtonText: 'Cool' })

  3. Don't overlook the importance of importing Swa's CSS file in your main JavaScript file.

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

Unable to use .click function to choose image within container

Apologies for the lengthy post, but I believe providing all details is essential to understanding the issue at hand. The following code snippet is intended to display the first image in a pop-up box when a user clicks on any of the images shown: <div ...

What is the best way to locate a particular JSON key value pair through JavaScript?

I'm in the process of creating a unique app that forecasts the weather for an upcoming event based on the city location specified. To achieve this, I am utilizing two APIs - one API provides an array of objects representing each event by an artist ent ...

What's the most efficient method to recursively nest an array of objects into a tree structure with the id serving as a reference point?

My goal is to organize the pages in my database in a hierarchical "tree" view. Each page has a unique ID and a parent property that indicates which page it is a child of. I am looking for an efficient way to recursively nest these objects so that each chi ...

The type check for the "list" prop failed while passing a JSON array. The expected type was an Array, but a String was received instead

I am encountering an issue with a json object, named jsonObject, that includes an array labeled tracks. I have been using this.jsonObject.tracks as an array in my methods and template (with v-for) without any issues in Vue. However, I am facing a problem w ...

Symfony2 compresses CSS and JS files to improve performance

Currently, I am attempting to execute php app/console assetic:dump in order to test my production environment. While my css file gets generated successfully, the js file does not. The following error message is displayed : C:\wamp\www\p ...

Is there a way to determine the number of options required for a select tag to become scrollable?

Please review these two <select> elements: <select> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option>one</option> <option&g ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

Divide text to reduce its width within the confines of a specific height on a div element

I've spent the past week scouring various forums, including stackoverflow, but I haven't been able to find a solution. In my responsive website, I'm using CSS flexbox to display dynamic menu items. Sometimes the text can be quite long, and ...

Exploring the JSON object tree through recursion using underscore and backbone

If I have a JSON object with nested arrays of unknown depths and I want to pass each array into a _.template function, how can I make that happen? Here's an example of what my JSON object might look like: $start_elements = array ( array( ...

Dividing a JSON array by a specific key using lodash underscore

I'm on a quest to extract the distinct items in every column of a JSON array. Here is what I aim to convert : var items = [ {"name": "Type 1","id": 13}, {"name": "Type 2","id": 14}, {"name": "Type 3","id": 14}, {"name": "Type 3","id": 13}, {"na ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Is it possible to incorporate additional sections by utilizing map and props in the given code snippet?

I have a component named CardItems.jsx which specifically defines the appearance of a card. Then, I also have Gotocart.jsx where there is a welcome section (similar to welcoming someone to their cart) and an order section at the end (for initiating an orde ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

When working with Express router callbacks, the Array.includes() method will always return false, the Array.indexOf() method will always return -1, and

After utilizing fs.readFile() and fs.readFileSync() functions to access the content of 'words_alpha.txt', I discovered that the file can be accessed publicly from this link: https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha. ...

Trigger an event within a linked component

I've been working on a connected component where I'm attempting to dispatch the clear action from. Here's a snippet of the code: import {createElement} from 'react'; import reduce from 'lodash/fp/reduce'; import {connect ...

Is there a vulnerability in the routing security of Angular/MEAN.io?

After setting up the MEAN stack (MongoDB, Express.js, AngularJS, Node.js) and launching the sample program from mean.io, I found a basic app where you can log in and create blog "articles" for testing purposes. To my surprise, when I removed the '#!& ...

Place the new item right under the chosen items within the nested list

My nested list with a collapse feature is almost complete. However, I am encountering an issue where I need to add content just below the selected item when I click on the "add" button. For example, in the attached demo, there is a nested list. If I select ...

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...