I have a Vue2 component that relies on Vuex to retrieve the currently selected node (infoNode) in order to show that node's data to the user. I have a beforeCreate function that uses Axios to retrieve the top level nodes and set the 'infoNode' as the first node as shown below:
async beforeCreate(){
const info = await axios.get('/ajax/company-info')
if(info.data){
this.$store.dispatch("setCompanyInfo", info.data)
}
// Function to retrieve top level node
const topLevel = await axios.get('/ajax/get-root-contents')
if(topLevel.data){
this.$store.dispatch("loadTopLevel", topLevel.data)
}
},
Below is the Vuex function to set the infoNode
loadTopLevel(state,node){
state.infoNode = node
},
Here is where I try to grab the infoNode data and display an icon from an array of valid icons
<v-icon size="6em" v-if="fileIcons[infoNode.data.filetype]">{{ fileIcons[infoNode.data.filetype] }}</v-icon>
Now, in my component, I have a computed prop that retrieves this infoNode from the store for display. The issue that I'm having is that the frontend is throwing an error stating 'e.infoNode.Data' is undefined'.
This error is being thrown before the request is completed. After the request completes, the frontend successfully displays the infoNode since the store is updated.
Is there a way for me to set this data in the store before the component attempts to grab it? I've tried a lot of variations of beforeCreate (async and non) as well as created/mounted.
CodePudding user response:
In your case beforeCreate() is async so the component renders before you set data to store.
You're displaying v-icon
if fileIcons
have specific entry (infoNode.data.filetype
), but at that moment infoNode
is undefined
or infoNode.data
is undefined.
In v-if you should check if infoNode
is not undefined and has entry you're searching for.
Something like this:
computed: {
hasEntry() {
if(infoNode && ('data' in infoNode)) return true
return false
}
}
//template
<v-icon size="6em" v-if="hasEntry">{{ fileIcons[infoNode.data.filetype] }}</v-icon>