Search code examples
javascriptfirebasevue.jsgoogle-cloud-firestorevuex

How to load firestore collection to Vuex State?


My goal is to load a firestore collection into the Vuex state and use it for multiple pages. I was trying to follow :
How to get collection from firestore and set to vuex state when the app is rendered?

I followed this post and either I am missing something or possibly the code is outdated? I am very new to Vuex so I could be doing something wrong but I am not sure.

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
const db = require('../components/fbInit')


Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    categories: []
  },
  actions: {
    fetchCategories({ commit }) {
      db.collection('one').get().then(querySnapshot => {
        if (querySnapshot.empty) {
          // eslint-disable-next-line no-console
          console.log('cannot find')
          //this.$router.push('/HelloWorld')
        } else {
          this.loading = false;
          var categories = [];
          querySnapshot.forEach(doc => {
            categories.push(doc.data());
          });

          commit("setCategories", categories);
        }
      });
    }
  },
  mutations: {
    setCategories(state, val) {
      state.categories = val;
    }
  }
});

store.dispatch("fetchCategories");

export default store;

One.vue

<template>
  <div class="flex-row justify-center ma-12">
    <ul>
      <li v-for="category in categories" :key="category.name">{{category.name}}</li>
    </ul>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { mapGetters } from "vuex";
// eslint-disable-next-line no-unused-vars

export default {
  computed: {
    categories() {
      return this.$store.state.categories;
    },

    ...mapGetters([])
  },
  methods: {
    ...mapActions(["fetchCatagories"])
  }
};
</script>

I tested to see if the firestore is connected and it displayed its contents. But I am getting this error: Uncaught TypeError: db.collection is not a function.

I have never been able to load my firestore collection into the Vuex store state and load it. Again I am new to using vuex so any help will be greatly appreciated

TLDR; Goal: Load firestore collection('One'), Store it in Vuex state, Use Vuex store to load the same data on multiple pages without having to call the data on every page.


Solution

  • store/index.js

    const store = new Vuex.Store({
    ....
    getters: {
        categories (state) {
            return state.categories;
        }
    },
    ....
    });
    

    One.vue

    export default {
    ....
        computed: {
            ...mapGetters(['categories'])
        },
    ....
    }