Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing route before long api call finishes overwrites vuex store

I have a long api call in my vuex store and if I change the route before it’s finished and dispatch the same action from another page with a quicker api call the first call will eventually overwrite the second call. The action looks like this:

async getData({ commit }, payload) {
  try {
    const params = {...};

    const res = await axios.get(`/data`, {
      params,
    });

    if (res.status === 200) {
      commit("setData", res.data);
    }
  } catch (error) {
    commit("setError", error.response);
  }
},

Is there a way to prevent this from happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to prevent the ‘last to finish’ async call from overwriting the state, you need to cancel any old actions so they don’t complete.

In your example, since you are using axios, the easiest option is to use an AbortController.

In your action, attach the controller to the axios method via the signal param:

const controller = new AbortController()

let result = axios.get('/foo/bar', { signal: controller.signal })

Then when you need to cancel it (i.e before calling a new action, simply call):

controller.abort()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading