Error message
Current usage
I am using typescript with vue, where the vue project was created using cli.
Problem
I am trying to read a string within an object that was retrieved from firebase realtime database, but is displaying type errors in the console.
Situation
I currently working on the navigation bar trying to get the text to display without errors. For this, I have all my textual data stored in a firebase realtime database.
I have a local vuex state that should store the textual data, a getter to retrieve it and then a mutator sync request to get the data from the database and store it in state as textual data.
In my App.vue file, I am calling the mutator sync request to get the textual data from the database and storing it in state.
Then, in my navigation.vue file, I am calling the textual data getter, to get the textual data object, to then reference the text I want.
It is strange because if I use a button to run a method that returns the result of calling the state for text item 'Home', it shows the correct string.
CodePudding user response:
@Dylan the template is being rendered before your getter has been set (which is normal). The error message in the console is pointing to the problem, it's trying to read .navigation
of undefined. So basically it's trying to read $store.getters.getTextualData.header.navigation...
but on initial load, header
does not yet exist (it's undefined as the error mentions).
My preference for solving this would be to have a computed property that returns the string once it's available, eg
computed: {
homeButtonText() {
return $store.getters.getTextualData?.header?.navigation.text.buttons.home
}
}
it will return undefined until it's set. Alternatively you can return a default
computed: {
homeButtonText() {
return $store.getters.getTextualData?.header?.navigation.text.buttons.home || 'Home'
}
}
The reason the method is returning the correct value is because the getter has had time to be set, so the text exists. Template rendering happens really early on. A good article and diagram can be found here.
Within your template you can then update it as below,
<router-link to="/">
{{ homeButtonText }}
</router-link>