Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Last active August 5, 2021 15:21
Show Gist options
  • Save lmiller1990/a4e9208a01707ff7c0e8447250fc6f13 to your computer and use it in GitHub Desktop.
Save lmiller1990/a4e9208a01707ff7c0e8447250fc6f13 to your computer and use it in GitHub Desktop.
<template>
<div id="app">
<p>
Pending: {{ $store.state.getInfoPending }}
</p>
<p>
{{ $store.state.getInfoData }}
</p>
</div>
</template>
<script>
export default {
created () {
this.$store.dispatch('getAsync')
}
}
</script>
import axios from 'axios'
const doAsync = (store, { url, mutationTypes, stateKey }) => {
store.commit(mutationTypes.PENDING)
setTimeout(() => {
axios(url, {})
.then(response => {
store.commit(mutationTypes.SUCCESS, response.data)
})
.catch(error => {
store.commit(mutationTypes.FAILURE)
})
}, 1500)
}
export default doAsync
/* To run this gist, make an app using the vue-cli and webpack-simple template.
* vue init webpack-simple some-app
* also you will need to `yarn add axios vuex lodash --save`
*/
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
import _ from 'lodash'
const createAsyncMutation = (type) => ({
SUCCESS: `${type}_SUCCESS`,
FAILURE: `${type}_FAILURE`,
PENDING: `${type}_PENDING`,
loadingKey: _.camelCase(`${type}_PENDING`),
stateKey: _.camelCase(`${type}_DATA`)
})
export const GET_INFO_ASYNC = createAsyncMutation('GET_INFO')
import Vue from 'vue'
import Vuex from 'vuex'
import doAsync from './async-util'
import * as types from './mutation-types'
Vue.use(Vuex)
const mutationTypes = {
SUCCESS: 'GET_INFO_SUCCESS',
FAILURE: 'GET_INFO_FAILURE',
PENDING: 'GET_INFO_PENDING'
}
const state = {
info: {},
}
const mutations = {
[types.GET_INFO_ASYNC.SUCCESS] (state, info) {
state[types.GET_INFO_ASYNC.loadingKey] = false
Vue.set(state, [types.GET_INFO_ASYNC.stateKey], info)
},
[types.GET_INFO_ASYNC.PENDING] (state) {
console.log(types.GET_INFO_ASYNC.loadingKey)
Vue.set(state, types.GET_INFO_ASYNC.loadingKey, true)
}
}
const actions = {
getAsync(store) {
doAsync(store, {
url: 'https://jsonplaceholder.typicode.com/posts/1',
mutationTypes: types.GET_INFO_ASYNC
})
}
}
export default new Vuex.Store({
state,
mutations,
actions
})
@lmiller1990
Copy link
Author

@padomu this was just example - importing it would be fine. As for your second comment - both ways are fine. This is just showing the concept for three different states.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment