JiriChara / vue-kindergarten

Modular security for Vue, Vuex, Vue-Router and Nuxt
MIT License
312 stars 24 forks source link

Asynchronous child #14

Closed karimStekelenburg closed 7 years ago

karimStekelenburg commented 7 years ago

Hi there! I'm working on my first Vue project and while looking for a good way to do role based stuff I came across your magnificent framework and tutorial. I've been following along and everything works like a charm except one thing. I'm obtaining the user's role through a REST api. This means of course that the child cannot be set on initialization because the role is not yet obtained and stored in the Vuex store.

Any workaround for this? Any way to lazyload the child while still keeping it accessible everywhere?

Thanks in advance

JiriChara commented 7 years ago

Hey @karimStekelenburg,

vue-kindergarten should work just well with asynchronous child, because whenever the roles of your user are changed in the store, Vue will make sure that all components are notified and updated (see. https://vuejs.org/v2/guide/reactivity.html).

This is how your store might look like:

export default {
  state: {
    user: null
  },

  actions: {
    fetchUserRoles({ commit }, userId) {
      commit('fetchRolesStart');

      return client.get(`/api/roles/${userId}`)
        .then((res) => {
          commit('fetchRolesSuccess', res);

          return res;
        })
        .catch((err) => {
          commit('fetchRolesError', err);

          return Promise.reject(err);
        });
    }
  },

  mutations: {
    // ...

    fetchRolesSuccess(state, { data }) {
      state.user = data;
    }

    // ...
  }
};

and your child getter:

Vue.use(VueKindergarten, {
  child(store) {
    return store.state.user;
  }
});

You can also define your child as combination of 2 states:

Vue.use(VueKindergarten, {
  child(store) {
    return () => {
      user: store.state.user,
      roles: store.state.roles
    };
  }
});

it really depends on how you design your store

bognix commented 7 years ago

Worked like a charm for me! Thank you :+1:

karimStekelenburg commented 7 years ago

Sorry for the late response, but I got it working as well! Thank you for your elaborate and clear answer and for your work on this in general. Such a sexy solution!

JiriChara commented 7 years ago

Awesome @bognix, @karimStekelenburg! Happy that it worked for you :+1: