I'm using vue-i18n
and trying to set my messages using an injected function but I'm having an issue understanding why my messages are set in the server but when it's hydrated in the client the messages are empty. As you can see I set the translations in the asyncData method by using a method I inject
. I can see the json in the server but once the client is hydrated they become an empty object again.. Am I wrong calling it in the asyncData method? I'm trying to move away from using store/vuex.
// pages/index.vue
// here's my code for my page
asyncData({ $setTranslations }) {
const data = fetch('/data') // fetch data from api
$setTranslations(data.language)
}
// /plugins/translate.js
// my translate plugin
export default(context, inject) {
inject('setTranslations', async (locale) => {
await setMsgsForLocale(locale)
})
// init i18n
app.i18n = new VueI18n({
locale: 'en', // default will change when data is retrieved
fallbackLocale: 'en',
messages: {
en: {},
es: {},
},
})
async function setMsgsForLocale(language = 'en') {
// fetch json
fetch(`/translations/${language}.json`)
.then(data => data.json())
.then((messages) => {
app.i18n.locale = language
// set messages here
app.i18n.setLocalMessage(language, messages)
return messages
})
}
}