N
Nuxt7d ago
Michi

i18n not working in single export default functions

Im trying to use i18n in a single file with a export default function bye using "useI18n()". But i get an error "Unhandled Promise Rejection: SyntaxError: Must be called at the top of a setup function"
3 Replies
kapa.ai
kapa.ai7d ago
Hi @Michi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- This error is related to using useI18n() in Nuxt 3 outside of the proper context. The useI18n() composable, like many other Nuxt and Vue composables, needs to be called within a specific context, typically inside the setup() function of a component or within certain Nuxt-specific functions. To resolve this issue, you have a few options: 1. If you're using this in a component, wrap your component with defineNuxtComponent instead of a regular export default:
export default defineNuxtComponent({
setup() {
const { t } = useI18n()
// Rest of your component logic
}
})
export default defineNuxtComponent({
setup() {
const { t } = useI18n()
// Rest of your component logic
}
})
2. If you need to use i18n in a store or other non-component file, you can use useNuxtApp().$i18n instead:
import { useNuxtApp } from '#app'

export const useAppStore = defineStore('appStore', {
state: () => {
return {
label: useNuxtApp().$i18n.t('welcome')
};
},
});
import { useNuxtApp } from '#app'

export const useAppStore = defineStore('appStore', {
state: () => {
return {
label: useNuxtApp().$i18n.t('welcome')
};
},
});
This approach is described in the Stack Overflow answer about using i18n in Pinia stores (https://stackoverflow.com/questions/77594888). 3. If you need to use i18n in other parts of your application, consider creating a plugin or using it within a Nuxt lifecycle hook where the context is properly set up. Remember that composables like useI18n() rely on being called in the right context during the component lifecycle. Using them outside of this context or asynchronously can lead to errors like the one you're experiencing. Stack Overflow: How to use i18n messages in a Nuxt3 pinia store (https://stackoverflow.com/questions/77594888) Nuxt Docs: Vue and Nuxt composables (https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai7d ago
<@477982233899302923> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Cue
Cue7d ago
Mind sharing an example of what this export might look like?
Want results from more Discord servers?
Add your server