Correct way to refactor `this.$store.state` into external file function


#1

Hi

I’m trying to reduce the cycolmatic complexity of some fetch API calls. One area where I’m going to reuse this function everywhere is in the catch clause of my API calls

.catch(e => {
        this.$store.state.ajaxStatusResult = false;
        if (e.response) {
          this.$store.state.ajaxMessage = e.statusText;
        } else {
          this.$store.state.ajaxMessage = "Network Error";
        }
      });

So essentially I just want to store this in an external file, import it into whatever .vue file and call it. But I’m having trouble with this. What is the correct way?

I’m building it in my main.js as such:

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    ajaxStatusResult: null,
    ajaxMessage: ""
  }
});

new Vue({
  ...
  store,
  ...
});

#2

It depends on if you want to use this logic for every API call or just some. If all, then you could use an interceptor. Fetch doesn’t have anything built in for this, but looks like there’s some libs: https://github.com/werk85/fetch-intercept

If you want to be selective about which API call uses this. Then you’ll want to take the export/import route. Which is to just simply export a utility function which you use to handle errors.


#3

Thanks James, I can look at the repo.

I had tried the export/import approach but a little confused on how to build the external file as some of it was originally referenced in the main.js file also


#4

If you’re referring to the fact your logic involves the store, then you’ll need to import your store or vue instance to your external file.

e.g.

utilities.js

import App from './main';

export function handleError () {
  App.$store.state.ajaxStatusResult = false;

  if (e.response) {
    App.$store.state.ajaxMessage = e.statusText;
  } else {
    App.$store.state.ajaxMessage = "Network Error";
  }
}

main.js

import { handleError } from './utilities.js'

const App = new Vue({
  ...
  store,
  ...
});

export default App;

#5

Thanks James!