Skip to content

Instantly share code, notes, and snippets.

@cosileone
Last active May 7, 2020 13:45
Show Gist options
  • Save cosileone/e5703747cb08ef75c2a0f4b0ab567dd4 to your computer and use it in GitHub Desktop.
Save cosileone/e5703747cb08ef75c2a0f4b0ab567dd4 to your computer and use it in GitHub Desktop.
//PostRepository.js
import db from "firestore"
import {
vuexStore
} from "@/store/index.js";
export default {
async setupRealtimeConnection(fn) {
return db.collection("posts")
.onSnapshot(fn(querySnapshot));
},
async addPost(post) {
db.collection("posts").add(post);
},
};
// --------------------------------------------------------------------------
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
import PostRepository from './PostRepository';
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
realtimePostsConnection: null,
},
mutations:{
SET_POSTS_CONNECTION(state, obj){
state.realtimePostsConnection = obj;
},
},
actions: {
async createPostsConnection: ({commit}) => {
var postsDocument = PostRepository.setupRealtimeConnection(function(querySnapshot) {
// do something with your querySnapshot stuff
});
commit('SET_POSTS_CONNECTION', postsDocument);
},
async destroyPostsConnection: ({commit}) => {
// whatever it takes to destroy db.collection connection here
commit('SET_POSTS_CONNECTION', null);
},
async addPost: ({ state }, post) => {
await state.realtimePostsConnection.add(post);
},
},
getters: {
realtimePostsConnection(state){
return state.realtimePostsConnection;
},
},
});
// -------------------------
// PostsComponentName.vue
export default {
name: 'PostsComponentName',
data() {
// ...
},
created() {
this.$store.dispatch('createPostsConnection');
},
beforeDestroy() {
this.$store.dispatch('destroyPostsConnection');
},
computed: {
...mapGetters([
'realTimePostsConnection',
]),
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment