0

I'm using vue.js to manage the user and I have this piece of code to initialize vue:

const app = new Vue({
    el: '#dashboard',
    i18n: i18n,
    data:{ store },
    router: router,
    created()
    {
      this.store.user.actions.getUser();
    }
});

Inside store I have:

const store =
{
  user:
  {
    state:
    {
      user: null
    },
    actions:
    {
      getUser()
      {
        //method to retrieve user usign axios
      }
    }
  }
}

In this way, the user is correctly initialized.

Now, I have also a vue component with the following:

computed:
{
  getUser()
  {
    console.log(this.$root.store.user.state.user)
  }
},
methods:
{
  init()
  {
    console.log(this.$root.store.user.state.user)
  }
},
created()
{
  this.init();
}

But the console.log(this.$root.store.user.state.user) inside the init() method results in null, while the one inside computed returns the actual user.

Why it's like this? Shouldn't the init() method returns the user anyway?

Thank you all.

  • https://stackoverflow.com/questions/42978826/cant-access-root-data-in-vuejs –  Jun 05 '21 at 15:25
  • Have you tried renaming `store` to `myStore` ? – IVO GELOV Jun 05 '21 at 15:51
  • @MuhammadAhmad Thank you: I have already seen that question, but in my case I would prefer not to use props, since the component I was talking about in the question is a page called up via vue-router – JacopoLelli Jun 05 '21 at 15:55
  • @IVOGELOV yes, I have already tried to rename `store`, but unfortunately the `init()` method always returns `null` – JacopoLelli Jun 05 '21 at 15:59
  • Actually, the `init()` is returning the user, but it does so before the axios request has been resolved. You should use computed getters instead. – Igor Moraru Jun 05 '21 at 16:17
  • @IgorMoraru Thanks Igor, this is what I feared: the problem of using cumputed getters is that the value is not always initialized when the component is created and consequently there are cases in which this value is not shown immediately on the page template. Is there a way to get `user` to be captured before the page is mounted (since `mounted()` returns `null`)? – JacopoLelli Jun 05 '21 at 16:34

1 Answers1

0

If you are able to change your init() method to return Promise - then you can wait for that Promise to resolve before instantiating the whole Vue application:

store.init().then(() =>
{
  const app = new Vue({
    el: '#dashboard',
    i18n: i18n,
    data:{ store },
    router: router,
    created()
    {
      this.store.user.actions.getUser();
    }
  });
});
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26