Skip to content

Instantly share code, notes, and snippets.

@34fame
Last active November 10, 2020 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 34fame/d2d04274022d68ee85d83523b128aae6 to your computer and use it in GitHub Desktop.
Save 34fame/d2d04274022d68ee85d83523b128aae6 to your computer and use it in GitHub Desktop.
Vuex store example with Firestore real-time updates
import Vue from 'vue'
import { uid } from 'uid'
import { instance as axios } from 'boot/axios'
import { firestore as fs } from 'boot/firebase'
const BASEURL = process.env.API_BASEURL + '/users'
const state = {
collection: {}
}
const mutations = {
SET_USER: (state, value) => {
Vue.set(state.collection, value.id, value)
},
DELETE_USER: (state, id) => {
Vue.delete(state.collection, id)
}
}
const getters = {}
const actions = {
addUser: (context, data) => {
try {
axios.post(BASEURL, {
id: uid(),
...data
})
} catch (err) {
console.error('store-users/addUser', error)
}
},
updateUser: (context, data) => {
try {
axios.put(BASEURL + '/' + data.id, {...data})
} catch (err) {
console.error('store-users/updateUser', error)
}
},
deleteUser: (context, id) => {
try {
axios.delete(BASEURL + '/' + id)
} catch (err) {
console.error('store-users/deleteUser', error)
}
},
bindUsers: ({ commit }) => {
fs.collection('users').onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
if (!change.doc.metadata.hasPendingWrites) {
commit('SET_USER', {
id: change.doc.id,
...change.doc.data()
})
}
}
if (change.type === 'modified') {
commit('SET_USER', {
id: change.doc.id,
...change.doc.data()
})
}
if (change.type === 'removed') {
commit('DELETE_USER', change.doc.id)
}
})
})
}
}
export default {
namespaced: true,
state,
mutations,
getters,
actions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment