Using the NuxtJS Strapi Module in Vuex

987 Views Asked by At

I am using @nuxt/strapi as a wrapper around Strapi for NuxtJS. For Vuex inside Nuxt I am using the namespaced modules mode, so my structure looks as an example like this:

store
├── user.js
├── posts.js
└── index.js

In a Vue project I would import Vue, Vuex, maybe Axios and then create a store instance const store = new Vuex.Store(storeOptions) and dispatch my initial actions or make some API calls from inside store/index.js.

Example for index.js in a vue project:

import Vuex from 'vuex';
import Vue from 'vue';
import user from './modules/user'
import posts from './modules/posts'
Vue.use(Vuex);
const storeOptions = { ... }
const store = new Vuex.Store(storeOptions)

if (user) {
  ...
  store.dispatch('startPageLoading', 'store');
  store.commit('SET_USER', user);
  await store.dispatch("getSomeData");
  ...
}

But in a Nuxt project the store and the strapi instances already were created in root_project/.nuxt/.... So what is the best way to use $strapi and $store inside store/index.js? Neither $strapi or $store are available in store/index.js

1

There are 1 best solutions below

0
Ilijanovic On

there is this nuxtServerInit action that gets executed on the server side after you open / refresh page.

You can only do it in index.js file

This is how your index.js could look like:

//index.js
export const state = () => ({
   someState: false
})


export const mutations = {
  SOME_MUTATION(state, payload) {
    ...
  }
}

export const actions = {
  SOME_ACTION({ state, commit }, payload) {
     ...
  },
  nuxtServerInit({ commit }, { $strapi }){
     //do here something on the server side...
  }
}

The documentation says if you added the strapi module to your project, you should be able to access it from the context. The context is the second argument from nuxtServerInit

Thats it. This is how a store could look like, nothing fancy.

You could dispatch / commit something from any component with

this.$store.commit("SOME_MUTATION")

They say its global available with this.$strapi

This module globally injects $strapi instance, meaning that you can access it anywhere using this.$strapi. For plugins, asyncData, fetch, nuxtServerInit and Middleware, you can access it from context.$strapi.