Reputation: 109
I am trying to do a very simple chat app. One of the components that control the submission of one message after "enter" is giving me this error:
Error in render: "TypeError: Cannot read property 'content' of undefined"
found in
---> <MessagesComponent> at resources/js/components/MessagesComponent.vue
<Messagerie> at resources/js/components/MessagerieComponent.vue
<Root>"
However, if I predefine the 'content' property in the data function as something like 'text123' it works perfectly without any errors, but it shows this message on the input field (textarea) which of course is not desirable. I had verified the code many times and I don't really know where the error could be. Can someone give an idea?
<template>
<div class="card">
<div class="card-header">john</div>
<div class="card-body">
<Message :message="message" v-for="message in messages" :user="user"/>
<form action="" method="POST">
<div class="form-group">
<textarea name="content" v-model="content" placeholder="Écrivez votre message" :class="{'form-control': true, 'is-invalide': errors['content']}" @keypress.enter="sendMessage"></textarea>
<div class="invalid-feedback" v-if="errors['content']">
{{ errors['content'].join(', ') }}
</div>
</div>
</form>
</div>
</div>
<script>
import Message from './MessageComponent'
import {mapGetters} from 'vuex'
export default {
components: {Message},
data(){
return {
content: '',
errors: {},
}
},
computed: {
...mapGetters(['user']),
messages: function(){
return this.$store.getters.messages(this.$route.params.id)
}
},
mounted() {
this.loadMessages()
},
watch: {
'$route.params.id': function(){
this.loadMessages()
}
},
methods: {
loadMessages(){
this.$store.dispatch('loadMessages', this.$route.params.id)
},
async sendMessage(e){
if(e.shiftKey === false){
this.errors = {}
e.preventDefault()
try{
await this.$store.dispatch('sendMessage', {
content: this.content,
userId: this.$route.params.id
})
}catch (e){
this.errors = e.errors
}
}
}
}
}
Upvotes: 0
Views: 696
Reputation: 29122
So the problem is that this line sets this.errors
to undefined
:
this.errors = e.errors
In your template you're then trying to access errors['content']
, which will fail. You can't access a property of undefined
.
I'm not exactly sure what that line is trying to achieve, perhaps e.errors
is not the correct property? The key thing is that you have to ensure that this.errors
remains an object. e.g.
this.errors = e.errors || {}
This will make the console error go away but to fix it properly would require some understanding of exactly what the value should be when e.errors
is undefined
.
Incidentally, there's no need to write errors['content']
in your template. You can just use errors.content
.
Upvotes: 2
Reputation: 186
I think it comes from errors, try to change errors for an array errors: [],
in case that doesn't work try adding a condition for errors before every condition of errors for example v-if="errors && errors['content']"
Upvotes: 1