nizzle
nizzle

Reputation: 1046

Where do I put my server REST logic in vue / vuex

In a Vue + Vuex application...

I have list of items. When I create a new item in the client, this item should also be created on the server. The server should supply the ID of the new iem.

So we need a round-trip before we can update the state.

Now, do I put this AJAX call in vuex 'actions' or in vuex 'mutations'? What's some best practices here...

Upvotes: 1

Views: 690

Answers (2)

Corentin PRUNE
Corentin PRUNE

Reputation: 388

I would add another level of abstraction :

You should split your api calls within another / other files and call these methods from your store actions

//store action
import * as apiService from '../api'

export const someAction = ({ commit }) => {
 apiService.getXXX()
 .then( result => {
  commit(SOME_MUTATION, result)
 })
 .catch( error => {
  commit(SOME_ERROR_MUTATION, error)
 })
}

Upvotes: 1

CD..
CD..

Reputation: 74176

In Vuex, mutations are synchronous transactions, so you'll want to do any asynchronous work (like AJAX calls) using actions.

Upvotes: 0

Related Questions