How to manage the logged in state of user in nativescript vue?
Asked Answered
D

1

0

I was wondering how to handle login/logout of the user so I did this:

store.commit('load_state');
store.subscribe((mutations, state) => {
  ApplicationSettings.setString('store', JSON.stringify(state));
});

new Vue({
  store,
  render: h => h('frame', [h(store.state.is_logged_in ? App : Login)]),
  created() {
    this.$store.commit('setNav', this.$navigateTo);
    if (this.$store.state.is_logged_in) {
      this.$store.dispatch('init');
    }
  },
}).$start();

please note that loadstate initially loads the state from applicationsettings. But the problem with this solution is that this.$store is not available in the child components of Login.vue What would be the correct way to do this?

Please note that I'm not using vue-router here.

Derange answered 12/9, 2019 at 12:16 Comment(0)
D
0

I was struggling with this problem for two days until I finally found the solution.

My problem was because I was using $navigateTo without specifying the frame, I was navigating the whole component. I discovered that store was only bound to the first component that is passed to the render function in main.js

Here is how my main.js looked:

new Vue({
  store,
  render: h => h('frame', [h(store.state.is_logged_in ? Main : Login)]),
  created() {
    this.$store.commit('setNav', this.$navigateTo);
    if (this.$store.state.is_logged_in) {
      this.$store.dispatch('init');
    }
  },
}).$start();

I discovered that If is_logged_in was true this.$store, or mapActions etc only worked in Main and it's child components, otherwise it would only work in Login and it's child components. Then I was reading This and saw the following code in the store code of the example:

import Vue from 'nativescript-vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({...});
Vue.prototype.$store = store;
module.exports = store;

So I added the line Vue.prototype.$store = store; to my own store definition and finally my problem was solved. This really gave me such a hard time. Hope I can save somebody.

Derange answered 12/9, 2019 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.