Reputation: 565
I have a vuejs + firebase project.
I have a three vuex store modules which are
back, common, front
My store folder structure is like this:
src/store
├───back
│ └───index.js
├───common
│ └───index.js
├───front
│ └───index.js
Without nuxtjs I can fetch user notifications like this
fetchUserNotifications({commit, getters}) {
let getUser = store.getters["common/getUser"];
return firebase
.database()
.ref("users/" + getUser.id)
.child("notifications")
.limitToLast(5)
.on("value", snapshot => {
commit("setUserNotifications", snapshot.val());
});
},
But with nuxt js getUser
returns undefined, I think thats because I have to fetch data's before the rendering.
I also added
setTimeout(() => console.log(store.state.front.user), 5000);
but everytime result is null. When I check Vuejs Developer Tools on Chrome, everything looks fine and my data is there.
I have searched the docs and found nuxtServerInit()
but couldn't figure out how to use it.
To be honest, I couldn't understand nuxtjs and need help to fetch data's easily like non-nuxtjs project.
Upvotes: 0
Views: 1499
Reputation: 26
From what I understand, your question deals primarily with how to setup store modules in NuxtJS. Here's a quick example of how I might setup your root store module based on what you've shared so far about setting and getting a user and handling the nuxtServerInit
function in the root store action:
// store/index.js
export const state = () => ({
user: null,
userNotifications: null
})
export const mutations = {
setUser(state, userData) {
state.user = userData
},
setUserNotifications(state, userNotifications) {
state.userNotifications = userNotifications
}
}
export const getters = {
getUser (state) {
return state.user
}
}
export const actions = {
nuxtServerInit ({ commit }) {
return httpClient.get('/url/to/get/user/data')
.then(({ data }) => {
commit('setUser', data)
})
}
}
// where you fetch notifications in a component or page
fetchUserNotifications({commit, getters}) {
let user = this.$store.getters.getUser();
return firebase
.database()
.ref('users/' + user.id)
.child('notifications')
.limitToLast(5)
.on('value', snapshot => {
commit('setUserNotifications', snapshot.val());
});
},
...
If you have any questions see the NuxtJS documentation on Module mode with Vuex store: https://nuxtjs.org/guide/vuex-store
Upvotes: 1