I have a Nuxt middleware file that fetches the session from an external api. This session is used to set things such as locale, so it's important that it is fetched before any page loads. Currently it looks like this:
middleware/session.js
import axios from 'axios'
export default function ({ store }) {
axios.get('http://example.com/getsession')
.then(response => {
store.commit('setSession', response)
})
.catch(() => {
store.commit('clearSession')
})
}
store/index.js
export const state = () => ({
session: {}
})
export const mutations = {
setSession (state, session) {
state.session = session || {}
},
clearSession (state) {
state.session = {}
}
}
export const getters = {
session (state) {
return state.session || {}
}
}
The session is fetched using Axios and stored in a Vuex store. However, since it is asynchronous, this data isn't available instantly, and plugins or other middleware that try to get the session from the store simply get an empty object (which is the default).
Examples where this breaks things:
session.user
. The session is still empty and therefore session.user
is undefined
at this point.Is there a way to await the response of the api call before proceeding? Or is there maybe a different/better way to perform this api call?
A middleware receives the context as the first argument. In universal mode, middlewares will be called once on server-side (on the first request to the Nuxt app, e.g. when directly accessing the app or refreshing the page) and on the client-side when navigating to further routes.
Nuxt has two hooks for asynchronous data loading: asyncData . This hook can only be placed on page components. Unlike fetch , this hook does not display a loading placeholder during client-side rendering: instead, this hook blocks route navigation until it is resolved, displaying a page error if it fails.
Nuxt generates router logic and its routes based on the directory and file structure for pages. For example, if we create a directory and file “about/index. vue”, Nuxt. js automatically creates the route “/about” for that page.
Nuxt Content is a git files based headless CMS that allows you to create a blog or documentation site from Markdown, JSON, YAML, XML, and CSV files. It includes: Full-text search. Static site generation support with nuxt generate. A Powerful QueryBuilder API (MongoDB like)
From the Nuxt documentation: "A middleware can be asynchronous. To do this, simply return a Promise or use the 2nd callback argument"
Therefore, something like this should work, since axios returns a promise:
import axios from 'axios'
export default function ({ store }) {
return axios.get('http://example.com/getsession')
.then(response => {
store.commit('setSession', response)
})
.catch(() => {
store.commit('clearSession')
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With