2 years ago

Syncing Vuex with the backend

Posted 2 years ago by Demers94

Hi everyone,

I'm building an online shop and using Vuex to manage the content of the shopping cart.

Here is my store at the moment :

const store = new Vuex.Store({
    state: {
        items: [
            {name: "iPhone 7"},
            {name: "Samsung Note 7"},

And here's how I'm using it in my main component :

    <li v-for="item in items">{{ }}</li>

computed: {
        return this.$store.state.items;

It works well with this very simple example, but it gets more complicated when I want to sync the cart content with the backend (since I'm storing the items in the session)

For example, when the page loads I want to load the existing cart content by querying the backend. Here's how I'm doing it right now :

// In app.js

// in the store
mutations: {
    getCartContent(state, data){
        axios.get('/api/cart').then(response => {
            state.items =;

actions: {

This is still manageable, but it means that if I want to do anything else with the cart (add an item, remove an item, update the quantity), I need to :

  • Create an action
  • Create a mutation
  • Dispatch the call to the action in my components (ex: to respond to a button click)
  • Commit the mutation from the action

Is this really the good way to do it?

It doesn't feel right to have all these AJAX calls specific to the cart in my store, which as far as I understand is just a big object to store all your data. Why is this big object responsible for doing all the backend calls and processing that data?

Any help on how to improve this is appreciated.


Please sign in or create an account to participate in this conversation.