capiono
capiono

Reputation: 2997

using helper functions in vuex

In vuex module I'm getting data (documents and favorites) from 2 different sources and I need to loop over the documents and assign favorites to a document.

I created a reusable function outside the vuex module to help me do this:

const bindFavoriteToDocument = (documents, favorites) => {
  // reset selected favorites
  favorites.forEach(item => {
    item.selected = false
  })
  documents.forEach(item => {
    var favs =
    favorites.filter(f => {
      var filter = f.favoriteDocuments.filter(
        d => d.document === parseInt(item.id) && d.source.toLowerCase().trim() === item.agency.toLowerCase().trim()
      )
      return !!filter.length
    }) || []

    favs.forEach(item => {
      item.selected = true
    })

    item.favorites = favs
    item.favoriteIds = _.pluck(favs, 'id')
    item.active = false
  })
  return documents
}

When everything the favorite objects are updated, I call this function to refresh the list of favorites assigned to a document.

  deleteFavorite: async ({ dispatch, commit, rootGetters }, payload) => {
    const response = await remove(config.PORTAL_API + 'api/favorite/delete/' + payload.id, rootGetters.token)
    if (response) {
      await dispatch('getFavorites')
      const documents = bindFavoriteToDocument(rootGetters['document/documents'], rootGetters['document/favorites'])
      commit('setDocuments', documents)
    }
  }

After editing a favorite, I'll seeing this error in the console:

Error: [vuex] Do not mutate vuex store state outside mutation handlers.

how do I create a new copy of documents and favorites in bindFavoriteToDocument that doesn't directly mutate the store state?

I have tried:

const bindFavoriteToDocument = (documents, favorites) => {
  let favoriteList = favorites
  let documentList = documents
  .
  .
  .
  return documentList
}

but that didn't work.

Upvotes: 1

Views: 1773

Answers (1)

Max Sinev
Max Sinev

Reputation: 6034

Just create mutation which will call bindFavoriteToDocument and set documents so you can avoid this warning:

  // in actions
  deleteFavorite: async ({ dispatch, commit, rootGetters }, payload) => {
    const response = await remove(config.PORTAL_API + 'api/favorite/delete/' + payload.id, rootGetters.token)
    if (response) {
      await dispatch('getFavorites')
      commit('bindFavoritesAndSetDocuments', { docs: rootGetters['document/documents'], favs: rootGetters['document/favorites'] } );
    }
  }

  //in mutations 
  bindFavoritesAndSetDocuments: (state, { docs, favs }) => {
      const documents = bindFavoriteToDocument(docs, favs);
      // set docs if necessary
  }

Upvotes: 1

Related Questions