Challenge
I am facing an issue while trying to fetch data from my database using vuejs + axios within a Laravel project. Locally, the axios request works fine and the data is displayed on the DOM after assigning it to variables. However, when deploying the same code to production, the axios request seems to take longer to execute, leading to a 'undefined property' error due to vuejs being ready before all the data is returned. This error persists even after multiple refreshes.
Possible Cause of the Problem
My assumption is that axios is not retrieving the data quickly enough for vuejs to display it, resulting in the undefined error
.
Attempts Made so Far
I have tried using v-if
statements on the objects dependent on the data, but it only hides the object if the data is not present. For example...
HTML
<!-- If user.name exists, display user.name -->
<div v-if="user.name">
@{{ user.name }}
</div>
JAVASCRIPT
<script>
new Vue({
el: '#container',
data: {
user: {}
},
mounted() {
this.getUserData();
},
methods: {
getUserData(){
axios.post('/user/get').then((response) => {
// Check the response was a success
if(response.data.status === 'success')
{
this.user = response.data.user;
}
});
},
}
})
</script>
However, this approach does not solve the issue and does not display anything when the data hasn't loaded yet.
Query
How can I ensure that the loaded data is displayed without encountering an undefined error? One solution I can think of is to allow the user to 'click to retrieve data' upon a failed attempt.
Additional Details
I am not using vue templates, child/parent structures, or any vue libraries. I am simply importing vue.js via CDN and using it on the page as shown above. I am uncertain if this method may have limitations, as my knowledge of vue.js is basic and this setup has been approved by my company and boss.