fix(nuxt): load payload after middleware and once final route is resolved (#7574)

This commit is contained in:
Daniel Roe 2022-09-16 11:15:10 +01:00 committed by GitHub
parent 5605f1ce18
commit c1ed6ecc3c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
import { defineNuxtPlugin, loadPayload, addRouteMiddleware, isPrerendered } from '#app' import { defineNuxtPlugin, loadPayload, isPrerendered, useRouter } from '#app'
export default defineNuxtPlugin((nuxtApp) => { export default defineNuxtPlugin((nuxtApp) => {
// Only enable behavior if initial page is prerendered // Only enable behavior if initial page is prerendered
@ -6,17 +6,16 @@ export default defineNuxtPlugin((nuxtApp) => {
if (!isPrerendered()) { if (!isPrerendered()) {
return return
} }
const prefetchPayload = async (url: string) => {
const payload = await loadPayload(url) // Load payload into cache
nuxtApp.hooks.hook('link:prefetch', to => loadPayload(to))
// Load payload after middleware & once final route is resolved
useRouter().beforeResolve(async (to, from) => {
if (to.path === from.path) { return }
const payload = await loadPayload(to.path)
if (!payload) { return } if (!payload) { return }
Object.assign(nuxtApp.payload.data, payload.data) Object.assign(nuxtApp.payload.data, payload.data)
Object.assign(nuxtApp.payload.state, payload.state) Object.assign(nuxtApp.payload.state, payload.state)
}
nuxtApp.hooks.hook('link:prefetch', async (to) => {
await prefetchPayload(to)
})
addRouteMiddleware(async (to, from) => {
if (to.path === from.path) { return }
await prefetchPayload(to.path)
}) })
}) })