I'm applying regular JavaScript functions (split
and join
) to a computed property which itself receives a state variable.
However I'm getting a Cannot read property 'split' of undefined"
error when component mounts because at that time my computed property user
is temporarily still empty.
Any way around that?
<template>
<div>
{{ userDob }}
</div>
</template>
<script>
import { mapState } from "vuex"
export default {
computed: {
...mapState({
user: state => state.dashboard.user || {}
}),
userDob() {
return this.user.date_of_birth.split("-").reverse().join("-")
}
}
}
</script>
You can set default value for the object in Vuex so it always has something to work with:
user: {
date_of_birth: "01-01-1970"
}
You can just display an empty string while it's getting the data:
userDob() {
try {
return this.user.date_of_birth.split("-").reverse().join("-")
}
catch(error) {
return ""
}
}