Skip to content

Instantly share code, notes, and snippets.

@davestewart
Created October 24, 2017 16:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davestewart/d938ea0b7705e5a66d3f5b9a62232c06 to your computer and use it in GitHub Desktop.
Save davestewart/d938ea0b7705e5a66d3f5b9a62232c06 to your computer and use it in GitHub Desktop.
Example of a Vuex service
import Vue from 'vue'
import _ from 'lodash'
import { compare, stringify } from 'utils/query'
import store from 'app/store'
/**
* Car loader service
*
* Removes responsibility of loading cars from the results store
*
* @property {boolean} loading
* @property {string} query
* @property {string} lastQuery
*
* @property {Function} search
* @property {Function} load
*/
const loader = new Vue({
data () {
return {
lastQuery: '',
lastGoodState: {},
loading: false,
}
},
computed: {
state () {
return _.cloneDeep(store.get('parameters/search'))
},
query () {
return stringify(this.state)
},
},
methods: {
/**
* Search all cars
*
* @return {Promise.<TResult>}
*/
search () {
this.loading = true
return store
.dispatch('results/search')
.then(() => {
this.loading = false
})
},
/**
* Load cars based on current query
*
* @return {*}
*/
load () {
// new queries, load data
if (!compare(this.query, this.lastQuery)) {
this.lastQuery = this.query
const state = this.state
this.loading = true
return store
.dispatch('results/browse')
.then(data => {
this.loading = false
if (data.results.length) {
this.lastGoodState = state
}
return data
})
}
// same queries, return existing data
const data = _.pick(store.state.results, 'cars', 'pagination')
return Promise.resolve(data)
},
/**
* Go back to the last good state
*/
back () {
store.set('parameters/search', this.lastGoodState)
}
}
})
window.loader = loader
export default loader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment