0

I'm trying to read/access my vuex store, but I get the error "Cannot read property '$store' of undefined, why?

This is what I have tried...

I created a Vuex store in a separate store.js file.

import Vuex from "vuex";
import Vue from "vue";
import { Auth } from "aws-amplify";

Vue.use(Vuex);
export const store = new Vuex.Store({
  state: {
    user: null
  },

  actions: {
    // AWS signup action.
    async signUp({ commit }, { username, password, firstName, lastName }) {
      const data = await Auth.signUp({
        username,
        password,
        attributes: {
          given_name: firstName,
          family_name: lastName
        }
      });
      console.log(data);
    }
  }
});

Next, I registered it in my main.js Vue instance.

import Vuex from 'vuex'
import Vue from 'vue'

// Provide an initial state object for Vuex.
import store from './util/store.js';
Vue.use(Vuex)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store: store, // Vuex mechanism to "inject" the store into all child components from the root component.
  render: h => h(App),
  router
})

I try to access the store ie. console.log(this.$store) <---- cannot find this.$store

In my reg,vue:

etc
</template>
<script>
  import AppNavbar from './Layout/AppNavbar'
  import AppFooter from './Layout/AppFooter'
  import { Card, Checkbox, Button, InfoSection } from 'src/components/UIComponents';

  export default {
    components: {
      Card,
      AppNavbar,
      AppFooter,
      InfoSection,
      [Checkbox.name]: Checkbox,
      [Button.name]: Button,
    },
    data(){
      return {
        form: {
          email: '',
          password: '',
          acceptTerms: true,
          
        }
      }
    },
    methods: {
   async submitReg() {
     console.log(this.$store)
     .........
3
  • 1
    where did you call this.$store? Commented Jan 30, 2021 at 13:23
  • In my reg.vue, inside methods i.e. console.log(this.$store) Commented Jan 30, 2021 at 13:24
  • 1
    please share the whole code including console.log(this.$store) Commented Jan 30, 2021 at 13:26

1 Answer 1

5

You missed to export default your store :

export default new Vuex.Store({
   ...

and use Vue.use(Vuex) once in the store creation, because Vue.use(Vuex) expects you define a store instance after that which is not the case in the main.js and it neglect the already created store.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.