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.

6
  • stackoverflow.com/questions/42978826/… Commented Jun 5, 2021 at 15:25
  • Have you tried renaming store to myStore ? Commented Jun 5, 2021 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 Commented Jun 5, 2021 at 15:55
  • @IVOGELOV yes, I have already tried to rename store, but unfortunately the init() method always returns null Commented Jun 5, 2021 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. Commented Jun 5, 2021 at 16:17

1 Answer 1

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();
    }
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @IVOGELOV, that's exactly what I did to solve my problem!

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.