I'm trying to use vuex as a layer between firestore and my vue application. My vuex store looks like this:
const store = new Vuex.Store({
state: {
posts: [],
},
mutations: {
add_post(state, post) {
state.posts[post.id] = post;
},
},
actions: {
async load_post(context, id) {
let post = await db
.collection('posts')
.where('post_id', '==', id)
.get();
post = post.docs[0];
post = {id, ...post.data()};
context.commit('add_post', post);
},
}
});
And inside my Vue component:
export default {
name: 'Post',
beforeMount() {
const id = this.$route.params.id;
this.$store.dispatch('load_post', id);
},
data() {
return {
id: this.$route.params.id
};
},
computed: {
content() {
return this.$store.state.posts[this.id];
}
}
};
Now, when navigating the website, the code seems to run fine. However, if I refresh the page then the content property becomes undefined. After some debugging, I've come to the conclusion that it tries to read from the store while loading(therefore being undefined), but when the store is ready nothing updates. So far I've tried watchers, vuex's mapState, nothing seems to work... any suggestions?
beforeMount
tocreated
, and changecomputed
tobeforeMount
. That will at least ensure the correct sequence of calls. – Len Joseph