Nuxt context.route not updated in asyncData()

1.5k Views Asked by At

I am using asyncData to fetch the current data for a page using the slug to find the data in my API (Strapi). This works fine for fresh page loads but fails when navigating to another language (nuxt-i18n). When navigating to the other language asyncData is called but the route hasn't been updated for some reason so the slug match fails. Refreshing the page manually updates the route and the slug then matches.

// pages/_slug/index.vue

<script>
export default {
  async asyncData({ params, route, $strapi, error, app, store, i18n }) {
    const path = route.params.slug // <- This is not updated on page navigation using language switcher
    const page = await $strapi.$pages.find({ slug: path, _locale: i18n.locale })
    if (page.length === 0) {
      error({ statusCode: 404, message: 'Page not found' })
      return {}
    }
    // Get the slug for this page in every locale.
    const localizedSlugs = {}
    for (const code of i18n.localeCodes) {
      localizedSlugs[code] = {
        slug: route.params.slug,
      }
    }
    for (const lang of page[0].localizations) {
      const pageLocalized = await $strapi.$pages.find({ id: lang.id, _locale: lang.locale })
      if (pageLocalized.length > 0) {
        localizedSlugs[lang.locale].slug = pageLocalized[0].slug
      }
    }
    await store.dispatch('i18n/setRouteParams', localizedSlugs)
    return { page: page[0] }
  }
}
</script>

The language switcher I'm using looks like this:

<template>
  <div class="language-switcher">
    <nuxt-link
      v-for="locale in availableLocales"
      :key="locale.code"
      :to="switchLocalePath(locale.code)">
      {{ locale.code }}
    </nuxt-link>
  </div>
</template>

<script>
export default {
  computed: {
    availableLocales() {
      return this.$i18n.locales
    },
  },
}
</script>

Any idea why route.params.slug (or route generally) is not updated after a client side navigation to a different language?

Edit: My current workaround is to not use NuxtLink component and instead use normal anchor tags like this:

    <a
      v-for="locale in availableLocales"
      :key="locale.code"
      :href="switchLocalePath(locale.code)">
      {{ locale.code }}
    </a>

This reloads the page and correctly loads the route params that asyncData is relying on to match a page with the API.

1

There are 1 best solutions below

0
On

Update: The issue has been fixed on [email protected]


Original answer

What version of nuxt-i18n and vue-i18n are you using?

I have encountered the same problem with nuxt validate(): Getting the route from nuxt context and matching it with API data in vuex store fails because the route is not updated.

For me it worked to downgrade to [email protected] or lower. It looks like this is an issue from 8.24.3 up.

I raised an issue here https://github.com/kazupon/vue-i18n/issues/1230 but I am unsure if it is to be fixed by vue-i18n or nuxt-i18n.