I am using msw.js as request mocking library.
However, some requests are triggered on development before the msw web worker is ready. I can be sure of because the first requests fail. I retry them in the UI with the DevTools and it works as expected.
Here my main.ts
:
import { createApp } from 'vue'
import { router } from './routes'
import { pinia } from './pinia.setup'
import App from './App.vue'
import { onUnhandledRequest } from './mocks/browser'
const prepareWorkers = async () => {
if (process.env.NODE_ENV === 'development') {
const { worker } = await import('./mocks/browser')
await worker.start({
onUnhandledRequest
})
}
return Promise.resolve()
}
prepareWorkers().then(() => {
const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')
})
As you can see, I am already following the deffered mounting recommandations without success and I am running out of idea.
I am using vite and it may also be something related to it as all files are downloaded from the vite dev server. Also the requests are triggered in a composable, outside of the function. As example:
// useMyStatefulComposable.ts
// instantiate it once for multiple composable instances
const allResquests = Promise.allSettled(urls.map(url => fetch(u)))
export const useMyStatefulComposable = () => {
// using the allRequests result inside the composable
return { myReactiveData }
}
CodePudding user response:
That the requests are instantly done in useMyStatefulComposable.ts without waiting for the application to be initialized is a mistake that needs to be fixed. If they should be done once, this needs to be done lazily:
let allRequests;
export const useMyStatefulComposable = () => {
if (!allRequests) {
allRequests = Promise.allSettled(urls.map(url => fetch(u)))
}
...
return { myReactiveData }
}
Considering that these are the results of allRequests
that need to be processed in useMyStatefulComposable
, the promises possibly need to be chained inside if (!allRequests)
either.