0

I have an action

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);
    })
}

and then on my component when the user click the submit button I just called the action via dispatch

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

Now i have sweetalert I'm confused how to implement it after a successful axios post request

I tried to put it inside my action 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 is on the action file. Should I call it inside my component like this?

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

Any idea on how can I implement this? Thanks

Im beginner in vuejs and vuex.

Community
  • 1
  • 1
Beginner
  • 1,700
  • 4
  • 22
  • 42
  • Have your action `return` the promise created by Axios. Then your last code snippet (in the component) will actually work. See [Returning Promises from Vuex actions](https://stackoverflow.com/questions/40165766/returning-promises-from-vuex-actions) – Phil May 20 '19 at 07:08
  • Have your action return the promise created by Axios - by using resolve? – Beginner May 20 '19 at 07:11
  • No, literally add a `return` before `axios.post`, eg `return axios.post(...)`. Axios creates a promise already so you don't need to create a new one. See https://vuex.vuejs.org/guide/actions.html#composing-actions and the other post I linked above – Phil May 20 '19 at 07:17
  • It is working inside the .then but i don understand why .catch is not catching the errors – Beginner May 20 '19 at 07:26
  • I tried to put a sweetalert inside the .catch but it is not working – Beginner May 20 '19 at 07:27

1 Answers1

0

I think the key question is that "this" may be not the "this" you want in store module, "this" in store module is different from "this" in components. So change the way you want to alert

  1. import swa in your store module

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

  2. do alert when axios compolete use code below

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

  3. never forget import swa's css file in main js
fbfatboy
  • 371
  • 1
  • 6