Question Conclusion:
A Vue component I am working on has the following data setup:
conversations: null,
currentConversation: null,
There is a method that runs on mounted()
to retrieve the user's conversations:
/**
* Method to retrieve the user's conversations.
*/
getConversations() {
axios.get('/api/user/conversations')
.then((response) => {
this.conversations = response.data;
})
.catch((error) => {
console.log(error);
})
},
The conversations are displayed in the <template>
using the following structure:
<template v-for="conversation in conversations">
<div class="conversation">
<p>
<!-- Template for each user -->
<template v-for="(user, index) in conversation.users">
{{ user.first_name }} {{ user.last_name }}<span v-if="index != (conversation.users.length - 1)">,</span>
</template>
</p>
</div>
</template>
However, the template for the current conversation causes an error as follows:
Uncaught TypeError: Cannot read property 'messages' of null
The currentConversation object is retrieved later through Ajax when a user selects a conversation to view.
By adding a v-if="currentConversation"
directive around the current conversation <template>
, the error is resolved. This raises the question: why does this workaround only apply to the current conversation and not to the conversations template?
Updated: Following suggestions from @wing and @Traxo, initializing with an empty array resolves the issue. However, it remains unclear why setting an empty array initially is required for currentConversation
but not for conversations
.