nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.74k stars 482 forks source link

`useLocaleHead` doesn't update on `switchLocalePath` #3206

Closed mrleblanc101 closed 13 hours ago

mrleblanc101 commented 1 week ago

Environment


Reproduction

https://github.com/capitalenumerique/interfaceqc

Describe the bug

I'm using the LanguageSwitcher exemple:

<script setup>
const { locale, locales } = useI18n();
const switchLocalePath = useSwitchLocalePath();

const availableLocales = computed(() => {
    return locales.value.filter((i) => i.code !== locale.value);
});
</script>

<template>
    <NuxtLink v-for="locale in availableLocales" :key="locale.code" :to="switchLocalePath(locale.code)">
        {{ locale.name }}
    </NuxtLink>
</template>

And I'm trying to implement the SEO tags using this in my app.vue:

<script setup>
const i18nHead = useLocaleHead();

useHead({
    htmlAttrs: {
        lang: i18nHead.value.htmlAttrs.lang,
    },
    link: [...(i18nHead.value.link || [])],
    meta: [...(i18nHead.value.meta || [])],
});
</script>

<template>
    <NuxtLayout>
        <NuxtPage />
    </NuxtLayout>
</template>

But the lang="fr-CA" does not update for lang="en-CA", but the URL and the app locale is updated. If I refresh the page, the lang attribute is correct: Image

Additional context

No response

Logs

No response

userquin commented 3 days ago

Change the lang attribute to use a function to avoid caching the value, useHead will call it:

useHead({
    htmlAttrs: {
        lang: () => i18nHead.value.htmlAttrs.lang, // <== THIS LINE
    },
    link: [...(i18nHead.value.link || [])],
    meta: [...(i18nHead.value.meta || [])],
});
mrleblanc101 commented 3 days ago

@userquin Thank you, will do. I see you closed as completed without linking to a commit, does this mean the documentation has been (or will be) updated ?

userquin commented 3 days ago

oh, can you send the link to the docs?

userquin commented 3 days ago

In fact, you should return the entire entry:

useHead(() => ({
    htmlAttrs: {
        lang: i18nHead.value.htmlAttrs.lang,
    },
    link: [...(i18nHead.value.link || [])],
    meta: [...(i18nHead.value.meta || [])],
}));
mrleblanc101 commented 3 days ago

Everywhere I could find useLocalHead in the documentation https://i18n.nuxtjs.org/docs/composables/use-locale-head#usage and here: https://i18n.nuxtjs.org/docs/guide/seo#feature-details

userquin commented 3 days ago

Pr welcome 🙏

userquin commented 13 hours ago

PR merged