I'm trying to load the data from an api with axios through a store action, but the SSR don't wait the action finish.
There is any away to do it?
nuxtServerInit({ dispatch }) {
return dispatch('core/load');
}
//core actions
import { list as categoryList } from '../../services/category';
export default {
load({ commit }) {
return categoryList().then(categories => {
commit('setCategories', categories);
});
}
};
//category action
import apiHttp from './api';
export function list() {
return apiHttp.get('/categories').then(response => response.data);
}
//api
import * as axios from 'axios';
import { API_URL } from '../config';
export default axios.create({
baseURL: API_URL //http://localhost:3000/
});
Thanks!
Can you verify that your 藡core/load` action returns a Promise?
You are right, axios does not return a "core" Promise. I think is a good idea add this information to the documentation.
nuxtServerInit({ dispatch }) {
const promise = dispatch('core/load');
console.log(promise instanceof Promise); //false
return promise;
},
Thank you! I really like this framework! :smile:
This is weird, what is the result of the console.log if it's not a Promise?
I want to find the solution :)
https://github.com/nuxt/nuxt.js/blob/593e12f348344c3b6608228738ef48e79a62fe91/lib/app/server.js#L58
Instead of check with intanceof you can use Promise.resolve;
promise = Promise.resolve(promise);
My code of the nuxtServerInit:
nuxtServerInit({ dispatch }) {
return Promise.resolve(dispatch('core/load'));
},
Could you try this code @danieloprado:
async nuxtServerInit({ dispatch }) {
await dispatch('core/load')
}
@Atinux
Just FYI, both solutions work for me
none of these solutions work for me
Thanks @Atinux the solution provided worked perfectly, and I see that a note has been added to the docs:
<< Note: Asynchronous nuxtServerInit actions must return a Promise to allow the nuxt server to wait on them.>>
I think it would be useful to include your solution above in the docs as well.
@fredski02 if it doesn't work for you, it's most likely because your action is not returning a Promise, so there is nothing to await.
agree with @cyrrill that this example (or similar) should be added to the docs; even after seeing the note it took me a bit to realize what exactly was going on with async nuxtServerInit
@Atinux @jpt
I've added your example to the docs in this PR: https://github.com/nuxt/docs/pull/518
Will merge, thanks @cyrrill
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Could you try this code @danieloprado: