So I have been trying to learn Vue, and I have a parent component which has an array thats empty initially, and an isLoading which is false. I use axios to fetch data inside the mounted hook, and update the array with the response data. To manage loading, I set isLoading to true before the axios call, and set it to false in the resolution of that axios call.
I tried consoling my isLoading data in mounted() and updated() hooks, and updated hook doesnt seem to be called at all.
The actual problem I am trying to solve is, I am passing these two data items inside provide() for another child component to use. The child component correctly shows the data that is fetched using axios in the parent, but isLoading prop is not updated inside the child component when accessed using inject. I have work arounds like I can check for the length of the array, but I really want to understand what is happening here and why.
Providing the valid code snippets below, and any help would be greatly appreciated.
Parent data, provide(), mounted and updated hooks:
data() {
return {
friends: [],
isLoading: false,
};
},
provide() {
return {
friends: this.friends,
toggleFavourite: this.toggleFavourite,
addFriend: this.addFriend,
isLoading: this.isLoading,
};
},
mounted() {
this.isLoading = true;
console.log("mounted -> this.isLoading", this.isLoading);
axios.get(*url*).then((res) => {
Object.keys(res.data).forEach((key) => {
this.friends.push({ ...res.data[key] });
});
this.isLoading = false;
console.log("mounted -> this.isLoading", this.isLoading);
});
},
updated() {
console.log("updated -> this.isLoading", this.isLoading);
},
Child inject:
inject: ["friends", "toggleFavourite", "isLoading"]
Child usage of isLoading:
<span v-if="isLoading">Loading...</span>
<div class="friends-container" v-else>
<friend
v-for="friend in friends"
:key="friend.id"
:name="friend.name"
:email="friend.email"
:hobbies="friend.hobbies"
:age="friend.age"
:rating="friend.rating"
:favourite="friend.favourite"
@toggle-fav="toggleFavourite"
></friend>
</div>