Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex store is undefined in NUXT middleware

I'm practicing NUXT and from tutorial its working well. mine fail when entering the NUXT middleware. the logic is if page is redirecting to other page it will enter middleware and fetch the result using axios.

middleware/search.js

import axios from 'axios';

export default function ({ params, store }) {
    console.log(store)

    return axios.get(`https://itunes.apple.com/search?term=~${params.id}&entity=album`)
        .then((response) => {
            console.log(response.data.results);
            store.commit('add', response.data.results)
        })
}

when entering here the store.commit('add'... will result

Cannot read property 'commit' of undefined

when I echo commit = undefined.

What I'm missing? I already tried this.$store.commit(...) still undefined.

VUEX

store/index.js

import Vuex from 'vuex'

const createStore = () => {
  return new Vuex.Store({
    state: {
      albums: []
    },
    mutations: {
      add (state, payload) {
        state.albums = payload
      }
    }
  })
}

export default createStore
like image 635
Winston Fale Avatar asked May 01 '18 16:05

Winston Fale


People also ask

What is middleware in Nuxt?

Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layout). Shared middleware should be placed in the middleware/ directory. The filename will be the name of the middleware ( middleware/auth. js will be the auth middleware).

Does Vuex have Nuxt?

The Vuex Store comes with Nuxt out of the box but is disabled by default. Creating an index. js file in this directory enables the store.

Can I use vue3 with Nuxt?

Nuxt 3 is the next generation of the popular hybrid Vue framework, which allows us to use Vue for building server-side rendered applications. Beta version was launched on 12 October 2021, bringing into Nuxt Vue 3, a new intro engine, a lighter bundle and adhook Vite.


2 Answers

I found a solution from the comments of the said tutorial but I want to share here if others struggle it too.

halt your development server ctrl+C

then restart the your dev server

npm run dev

then VUEX will be seen now in the middleware tnx

like image 81
Winston Fale Avatar answered Sep 22 '22 09:09

Winston Fale


Restarting the Dev Server worked for me as well. It seems Vuex isn't reloaded when changes are made.

Run npm run dev and it should work.

like image 34
Tilo Flasche Avatar answered Sep 20 '22 09:09

Tilo Flasche