Ajax call does not work in SSR mode if called from a function in store/index.js

connecteev
0
connecteev
commented 7 months ago

Version

v2.9.2

Reproduction link

http://www.nourl.com

Steps to reproduce

Ajax call does not work in SSR mode if called from a function in store/index.js

This does not work.
In the console, you see "make ajax call'", but never the line after the Ajax call:

console.log('result of ajax call:', res);

Code:

import axios from 'axios';

export const state = () => ({
  posts: [],
  page: 0,
  lastPage: null,
});

export const getters = {
  getPosts(state) {
    console.log('getPosts', state.posts);
    return state.posts;
  },
};

export const mutations = {
  appendPosts(state, newPosts) {
    console.log('appendPosts before', state.posts.length);
    state.posts = state.posts.concat(newPosts);
    console.log('appendPosts after', state.posts.length);
  },

  async retrievePosts(state) {
    console.log('retrievePosts');
    state.page++;
    try {
        console.log('make ajax call', process.env.backendPublicApiPrefix, state.page, '/' + process.env.backendPublicApiPrefix + '/posts?page=' + state.page);
        let res = await axios.get('/' + process.env.backendPublicApiPrefix + '/posts?page=' + state.page);
        console.log('result of ajax call:', res);

    } catch (e) {
      console.log('an error happened');
    }
  }
};

export const actions = {
  nuxtServerInit({ commit }) {
      //
  },
  retrievePosts(context) {
    context.commit("retrievePosts");
  }
};

And it is triggered from asyncData() using:

      context.store.dispatch('retrievePosts');
  • Note that this works fine (ie the Ajax call gets triggered and the output is shown in the console) in "client" mode, if you navigate from one page to another via a nuxt-link.
  • Also note that this same Ajax call works fine in SSR mode if you call it from asyncData(), which is why this leads me to believe there might be a bug here.

What is expected ?

Ajax call should work in SSR (universal) mode

What is actually happening?

Ajax (axios) never gets called if it is located in the vuex store/index.js file

bug
0
aldarund
998
aldarund
commented 7 months ago

mutations is a sync operations. For async you should be using actions, not mutationsts.
https://vuex.vuejs.org/guide/mutations.html#mutations-must-be-synchronous

0
connecteev
0
connecteev
commented 7 months ago

@aldarund see https://github.com/HendraPB/nuxt2-infinite-scroll/blob/master/src/store/index.js
that's what I was trying to replicate….he's doing an async await from within a mutation…so why does this work?

0
Informations
Bug ReportOpen
#c9777 - Created 7 months ago