How I can call NuxtServerInit correctly? - vue.js

When i try to call rest api with nuxtServerInit on Vuex store it don't call, but if call rest api on components or page it works.
store/index.js
import axios from 'axios'
export const state = () => ({
news: [],
})
export const mutations = {
SET_NEWS(state, posts) {
state.news = posts
}
}
export const actions = {
async nuxtServerInit({ commit }, ctx) {
const res = await axios.get('https://api/news.json')
commit('SET_NEWS', res.data)
},
}
export const getters = {
getNews(state) {
return state.news
}
}
pages/news/index.vue
computed: {
getNews() {
return this.$store.getters.getNews
}
}

Try calling your API like this in your vuex actions:
export const actions = {
async nuxtServerInit({ commit }, { req }) {
const res = (await this.$axios.$get('https://api/news.json')).data
commit('SET_NEWS', res)
},
}

Related

Vuex action not works with namespaced inside Nuxt fetch

I am building my own small project. When i try to access states from main store (index.js) inside of nuxt fetch method all works fine, but while i am trying to access from namespaced(store/photos.js) store it wont work. Here is my code.
store/index.js ( Works )
export const state = () => ({
fetchedData: []
})
export const mutations = {
setData: (state, data) => {
state.fetchedData = data;
}
}
export const actions = {
async get(vuexContext) {
const requestedData = await this.$axios.get("https://jsonplaceholder.typicode.com/users");
vuexContext.commit('setData', requestedData.data);
},
}
my Component:
<script>
import { mapState, mapActions } from 'vuex'
export default {
async fetch({ error,store })
{
try {
await store.dispatch('get');
} catch (error) {
console.log(error);
}
},
computed: {
...mapState(['fetchedData'])
}
};
</script>
store/photos.js ( Does not works )
export const state = () => ({
list: []
});
export const mutations = {
setPhotos(state, data) {
state.list = data;
}
};
export const actions = {
async getPhotos(vuexContext, context) {
const requestedData = await this.$axios.get(
"https://jsonplaceholder.typicode.com/photos"
);
vuexContext.commit("setPhotos", requestedData.data);
}
};
Same Component but modified
<script>
import { mapState, mapActions } from 'vuex'
export default {
async fetch({ error,store })
{
try {
await store.dispatch('photos/getPhotos');
} catch (error) {
console.log(error);
}
},
computed: {
...mapState({
list : 'photos/list'
})
}
};
</script>
Thanks in advance.
namespaced: true,
You can add this to your index.js file. Hope this will work.
Reference link:
Try this

How to dispatch store actions in namespaced modules ( NuxtJS)?

I have made lots of research and since keywords are always similar I cannot find a correct way of usage store modules in nuxtjs. I will shorten the codes to make it readable. In my nuxtjs application, I am trying to reach my vuex modules in my home.page but instead I get
pages/index.vue
TypeError
Cannot read property 'then' of undefined
created() {
this.$store.dispatch('articles/fetchIndexArticles')
.then(() => this.$store.dispatch('videolessons/fetchIndexVideolessons'))
.then(() => {
While creating modules first in the store folder i have created an index.js file:
import Vuex from "vuex";
import articles from "./modules/articles";
// ...
import videolessons from "./modules/videolessons";
const debug = process.env_NODE_ENV !== 'production';
export const store = new Vuex.Store({
modules: {
articles,
books,
members,
pages,
status,
user,
videolessons,
},
strict: debug,
plugins: [],
})
and basically my modules are similar to my articles module:
const getDefaultState = () => {
return {
indexArticles: [],
}
}
const state = getDefaultState()
const getters = {
indexArticles (state) {
return state.indexArticles
},
}
const mutations = {
fetchStart (state) {
state.loading = true
},
fetchEnd (state) {
state.loading = false
},
setIndexArticles (state, pArticles) {
state.indexArticles = pArticles
state.errors = {}
},
setError (state, errors) {
state.errors = errors
},
resetState (state) {
Object.assign(state, getDefaultState())
}
}
const actions = {
// ...
async fetchIndexArticles ({ commit }) {
try {
const response = await articlesService.fetchIndexArticles()
commit('fetchStart')
commit('setIndexArticles', response.data)
commit('fetchEnd')
return response
} catch (error) {
commit('setError', error)
this._vm.$q.loading.hide()
}
},
...
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
and in my index page:
<script>
import store from '../store/'
export default {
computed: {
indexarticles() {
return this.$store.getters['articles/indexArticles'];
}
},
created() {
this.$store.dispatch('articles/fetchIndexArticles')
.then(() => this.$store.dispatch('videolessons/fetchIndexVideolessons'))
...
.then(() => {
this.isLoading = false;
});
}
};
</script>
<template>...</template>
can you help to correct my store modules?
Thanks
ps:
videolessons.js
const getDefaultState = () => {
return {
indexvideolessons: [],
}
}
const state = getDefaultState()
const getters = {
indexVideolessons (state) {
return state.indexvideolessons
},
}
const mutations = {
setIndexVideolessons (state, pVideolessons) {
state.indexvideolessons = pVideolessons
state.errors = {}
},
}
const actions = {
async fetchIndexVideolessons ({ commit, dispatch }) {
try {
const response = await videolessonsService.fetchIndexVideolessons()
commit('setIndexVideolessons', response.data)
return response
} catch (error) {
commit('setError', error)
}
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}

Nuxt nuxtServerInit now being called

I am trying to setup the store/index.js in Nuxt and don't understand why nuxtServerInit is not being called. I have added the console.log to test it out, but it doesn't seem to work or output the log.
import Vuex from 'vuex'
import axios from 'axios'
const createStore = () => {
return new Vuex.Store({
state: {
loadedPosts: []
},
mutations: {
setPosts(state, posts) {
state.loadedPosts = posts;
}
},
actions: {
nuxtServerInit(vuexContext, context) {
console.log('Init works!');
return axios.get("<firebase.link>")
.then(res => {
const postsArray = []
for (const key in res.data) {
postsArray.push({...res.data[key], id: key})
}
vuexContext.commit('setPosts', postsArray)
})
.catch(e => context.error(e))
},
setPosts(vuexContext, posts) {
vuexContext.commit('setPosts', posts)
}
},
getters: {
loadedPosts(state) {
console.log("Here we go",state.loadedPosts);
return state.loadedPosts
}
}
})
}
export default createStore
Fixed it!
The app was in spa mode instead of universal.

Using Axios within nuxtServerInit()

I need to get remote data to be displayed in every pages.
This call is perfomed in store/index.js:
export const state = () => ({
contact: {
hello: "World"
}
});
export const actions = {
async nuxtServerInit({ commit, state }) {
const { contactData } = await this.$axios.get("/contact");
commit("SET_CONTACT", contactData);
}
};
export const mutations = {
SET_CONTACT(state, contactData) {
state.contact = contactData;
}
};
Problem is that the value of contact turns to undefined in the store, whereas expected content is retrieved through Axios (the retrieved content is displayed in the SSR console...)
What am I missing here?
export const actions = {
async nuxtServerInit({ commit, state }, {app} ) {
const { contactData } = await app.$axios.get("/contact");
commit("SET_CONTACT", contactData);
}
};

Can't get state stored by Vuex in ~/plugins/axios.js

I have problem to get token stored by Vuex in ~/plugins/axios.js. Hope your guys take a look for me please.
My Vuex: ~/store/index.js
export const state = () => ({
authUser: null,
token: null
})
export const mutations = {
SET_USER: function (state, user) {
state.authUser = user
},
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
}
export const actions = {
async nuxtServerInit ({ commit }, { req }) {
...
},
async login ({ commit }, { username, password }) {
...
}
}
const store = () => new Vuex.Store({
state,
mutations,
actions,
modules: {
feed,
users,
notification,
messenger
}
})
export default store
const VuexStore = () => {
return store
}
export { VuexStore }
~/plugins/axios, which VuexStore.state is not data!
import axios from 'axios'
import {VuexStore} from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/'
})
console.log(VuexStore.state.token) // Null data
export default api
Console log is:
ƒ VuexStore() {
return store;
}
Not tested but you could use something like:
~/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = () => ({
authUser: null,
token: null
})
const mutations = {
SET_USER: function (state, user) {
state.authUser = user
},
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
}
const getters = {
...
}
const actions = {
async nuxtServerInit ({ commit }, { req }) {
...
},
async login ({ commit }, { username, password }) {
...
}
}
export default new Vuex.Store({
state,
actions,
mutations,
getters,
modules: {
...
}
});
~/plugins/axios.js
import axios from 'axios'
import VuexStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/'
})
console.log(VuexStore.state.token)
export default api