The /api/user/
request to make $auth.loggedIn
available happens after client already loads/started loading. This makes some of my modules render and then disappear after $auth.loggedIn
has turned true/false, making everything look messy on page load.
It would be ideal if the call to /api/user/
happened in the same way an asyncData request works so that $auth.loggedIn
is available before anything renders. Is there any setup/config that makes this possible ? I'm using the universal mode.
You can use the middleware defined in Nuxt here In your case you could do your request on /api/user
before like that, in a middleware called userLoggedIn
for example.
export default function (context) {
// Here we return a Promise in the middleware to make it asynchronous
// Cf doc https://nuxtjs.org/guide/routing#middleware
// So we return a promise that can only be resolved when the function resolve is called
return new Promise(resolve => this.$axios.$get('/api/user'/).then((user) => {
if (!user) {
console.log('NOT LOGGED');
// Do something if not logged, like redirect to /login
return context.redirect('/login');
}
resolve(user);
}));
}
I made a proposition with $axios but of course you can change it. You just need to keep the middleware and the promise to have an asynchronous middleware.
Then on your page waiting for the query, you can add:
export default {
middleware: [
'userLogged',
],
data() {...}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.