0
votes

I'm trying to get data from firebase using Vuex. I'm communication with firebase in action, commit the data to mutations and getters will get data from state. Then I want to display state data in App.vue.

In App.vue component, I wrote dispatch in mounted function and try to get data from Vuex. However I get error "TypeError: this.$store.dispatch is not a function", and when I inspect state it says undefined. Are my actions and mutations wrote correctly? Why do I get that error?

store.js
import Vue from 'vue';
import Vuex from 'vuex';
import firebase from 'firebase';

Vue.use(Vuex);

export default new Vuex.mapState({
    state: {
        notebooks: [],
    },
    getters: {
        getItems: (state) => {
            return state.notebooks;
        },
    },
    mutations: {
        setItems: function(state, notebooks) {
            state.notebooks = notebooks;
        },
    },
    actions: {
        async getTodos({ commit }) {
            var notebooksRef = await firebase.firestore().collection('notebooks');
            const notebookList = [];
            notebooksRef.onSnapshot((snap) => {
                snap.forEach((doc) => {
                    let notebooks = {
                        id: doc.id,
                        notebook: doc.data(),
                    };
                    notebookList.push(notebooks);
                });
                commit('setItems', notebookList);
            });
        },
    },
});

App.vue
<template>
    <div id="app"></div>
</template>

<script>
export default {
    name: 'App',
    computed: {
        notebooks: function() {         
            return this.$store.state.notebooks;
        },
    },
    mounted() {
        this.$store.dispatch('getTodos');
    },
};
</script>
main.js

import Vue from 'vue';
import App from './App.vue';
import store from './store';
import './firebase';

Vue.config.productionTip = false;

new Vue({
    store,
    render: (h) => h(App),
}).$mount('#app');

firebase.js
import firebase from 'firebase';

const config = {
    apiKey: '****',
    authDomain: '****',
    databaseURL: '****',
    projectId: '****',
    storageBucket: '****',
    messagingSenderId: '****',
    appId: '****',
};
// Initialize Firebase
firebase.initializeApp(config);


1

1 Answers

2
votes

Try export default new Vuex.Store({ in your store.js file.