Async code in App Plugins
-
hello,
so I’m in the process of migrating from 14.1 to 15.8 and trying to move some initialization code over to ‘App Plugins’. I’m using vue-apollo and previously I was adapting ‘main.js’ in order to first setup and then pass the ‘ApolloProvider’ object to Vue.
I’m trying to move this code to a separate plugin now. However, I doubt this actually makes sense, since I’m executing some ajax calls during setup of Apollo and ‘App plugins’ seem not to take this possibility into account. They do not expect a promise, but rather simply execute the exported default function. So my only possibility would be to make this function block and wait for reponses (or timeout). But maybe I just miss something.
How should we deal with async code in ‘App plugins’?Greetings,
John -
If you really need async calls to initialize your plugin you should look at the boot plugin : http://quasar-framework.org/guide/app-plugins.html#Special-App-Plugin-Boot
This is a special plugin that let’s you launch the app when your are ready, after recieving the ajax callback in your case.
-
hi Slade,
thanks I will try. Async code during initialization, is it that uncommon?
John
-
I don’t have enough Vue or Quasar experience to say if it is right or wong to do that. I even did it using the boot plugin at first, but it felt dirty. So i changed my code and used the vuex store on the beforeMount event of my app.
-
I have just found this thread. I’m new to quasar and I was need ajax call to validate token found in localStorage. I failed to do it with regular plugin and I searched for solution. @Slade suggestion to add it to “boot” plugin works really good. Is there something that I’m missing or doing wrong with this approach?
-
@zmilan just make sure you read the corresponding docs. The
boot
plugin is special -
@benoitranque yes I read it and I understand that part. My code works exactly like I expected, but what I’m asking is there some “hidden” things that I don’t see at the moment about this usage.
Here is complete boot plugin code:
import api from ‘src/api’// leave the export, even if you don’t use it
export default ({ app, store, Vue }) => {
let tokenKey = api.getTokenKey()
let token = localStorage.getItem(tokenKey)
// assign api to Vue for easier access, like this.$api
Vue.prototype.$api = apiif (!token || token === ‘undefined’) {
/* eslint-disable-next-line no-new */
new Vue(app)
}api.checkToken(token)
.then(() => {
store.commit(‘apiAuth/changeIsGuest’, { status: false }, { root: true })
store.commit(‘apiAuth/changeToken’, { token: token, store: false }, { root: true })
})
.catch(() => {
// we wish to remove token so we don’t need to check it again on page refresh
localStorage.removeItem(tokenKey)
})
.finally(() => {
/* eslint-disable-next-line no-new */
new Vue(app)
})
}Thanks in advance for any suggestion