Struggling with asynchronous calls, I've realized this question has been answered many times before. Despite trying numerous suggested approaches without success, I would truly appreciate any help. Progress has been made recently, but I still consider myself a beginner.
In my controller.js file, there is an asynchronous call to a database that should return all the games from a 'Games' table and store them in an 'allGames' variable of type Array:
async getAllGames ({ request, response }) {
const allGames = await Game.all()
return response.json({
status: 'success',
data: allGames
})
}
The fetchAllGames function is executed when the page loads:
created () {
this.fetchAllGames(this.myCallback)
},
methods: {
myCallback (response) {
this.allGames = response
},
fetchAllGames (callback) {
axios
.get('/fetch_games')
.then(response => {
callback(response.data.data)
})
}
}
Everything appears to be working fine, and it's worth mentioning that VueJS is being used here.
Printing 'allGames' using
{{ allGames }}
displays the array of all games from the database as expected.
Accessing the second game by
{{ allGames[1] }}
works correctly.
Trying to display the ID of the second game using
{{ allGames[1].id }}
shows the ID with hot reload. However, upon manual page refresh, while the ID is still visible, you may encounter
[Vue warn]: Error in render: "TypeError: _vm.allGames[1] is undefined"
in the console.
The issue lies in needing to pass 'allGames' to another Component where it's currently being passed as 'undefined'.
I would greatly appreciate any insights or guidance on this matter. Despite trying various approaches and troubleshooting for some time, the solution seems to elude me. The same code works smoothly in a different component, so I'm certain I must be overlooking something crucial.