Vue/ Vuex: Async Moralis Calls

Hi everyone I am developing dApp on Vue2 and using the state management plugin Vuex. I got a main component which containing a few child components, which calling Moralis functions such as get user wallet’s address, balance etc whereas I will trigger the Moralis.start() function at the main component (might look at the simple architecture diagram below).

I encountered encountered some difficulties when doing as I always get errors like:

  • Error: Web3Api not initialized, run Moralis.start() first
  • Error: Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called, but is not finished yet

Could anyone please let me know how should I arrange those function calls? Please let me know if you need further information! Thanks in advanced for your kind help.

Try running enableWeb3() only once and in one place at App.vue or your base component.

It looks like you are attempting to call Web3Api functions as soon as your other components load or at least before Moralis.start finishes. With Vuex, what you could try is await your Moralis.start() and then set a state after it. And then only run Web3Api or Moralis functions based on this state.

react-moralis, the React wrapper around the Moralis SDK, uses an app level context / provider so you have access to things like isInitialized so you can run code only if isInitialized (Moralis is initialized) is true. You can probably do something similar in Vue.

1 Like

Thanks a lot for your suggestion! I will try to add a state to it.