1
votes

I have a lib which imports the vuex store

import {store} from "./index"

and that index file has an constant export like

export const store = new Vuex.Store({ ...

in the file I'm doing the import, I wanted to use something from the store after the import, but store was undefined.

if I wrapped my store access in a setTimeout like

setTimeout(()=>{
  // use store normally now..
},0)

it works.

Why? I'm guessing this isn't specific to Vuex but I don't know why it's happening.

2

2 Answers

1
votes

This is probably a case of circular dependency. Circular dependencies compile in webpack, but you get bugs at runtime.

Assuming you have files A and B and the dep chain is like A -> B -> A, then when B tries to import A, it still hasn't got to export stuff (because import statements precede statements that aren't import statements).

So import default ./A from B immediately returns undefined.

So either: make the B export a function that is somehow called after the A export is called, or create a module C that both A and B depend on that somehow fixes this circular dependency.

0
votes

I'm guessing you are loading things out of order or your setup is a little off.

I would try injecting the store into your Vue instance, then you can assume it will be available in all sub components.

main.js

import {store} from "./index"

new Vue({ 
  el: '#app',
  store,
  render: h => h(App)
})

Now in any child components you will have access to your store via this.$store