0
votes

I am looking for a way to change some data values inside component if an API call made by a vuex action fails. Currently, I do it by adding a try-catch inside my actions and throw the error and then catch the error inside the component by using another try-catch. Something like this:

Component 1

async method() {
 try {
    this.VUEX_ACTION();
 }
  catch (e) {
    /* this method changes the values inside data */
    this.componenntMethodToExecute();
 }
}

Vuex

VUEX_ACTION() {
 try {
   API_CALL()
 }
 catch (e) {
   throw e;
 }
}

The problem with this approach is that I've to wrap all my store actions calls in components inside try-catch again and again. One solution that I've found is to subscribe to the actions/mutation in Vuex and change my data inside component accordingly. But again that'd involve adding subscribers in components.

Also, I can't keep all my data values of component in Vuex as I use/change a lot of data values in my component and moving them to Vuex would need having actions/mutations of their own.

Another way I tried to get my job done is passing a function from the component to Vuex by binding function's 'this' context to current component. This function changes the data values that I want to change. It does my job but I am not sure if it's a good practice to pass a function's reference to vuex. Can you suggest a better solution or is this the way to go about it?

1
"I've to wrap all my API calls inside try-catch again and again" 👈 why is that a problem? – Phil
Should be "wrap all my actions in components inside try-catch". I'll update the question. – Himanshu

1 Answers

0
votes

I'm not sure I understood your problem correctly. Are you looking for something like this?

Vuex:

VUEX_STATE: {
    e: {}
}
VUEX_MUTATIONS: {
    e: (state, e) => state.e = e
}
VUEX_GETTERS: {
    error: state => state.e
}
VUEX_ACTIONs: {
    apiCall({ commit }) {
        try {
            API_CALL()
        }
        catch (e) {
            commit('e', e)
        }
    }
}

Vue component scripts. mapGetters(['error']) will only need to be included in components where you want to show the error. mapGetters(['apiCall']) only needs to be included in components where you want to call vuex actions.

computed: {
    ...mapGetters([
        'error'
    ]),
    changeDataValueHere() return this.error ? 'changed' : 'value if no error from api call',
    altChangedDataValuesHere() return this.error ? {a: 'changed', b: 'changed' ...} : {a: 'unchanged', b: 'unchanged' ...}
},
methods: {
    ...mapActions([
        'apiCall'
    ])
    apiAction() {
        this.apiCall
    }
}

Like this, there's no need for a try-catch block in the component.