I am trying to make component that needs object array to function. I am passing it from parent to child using props.
I am getting the data from API using axios.
Since the objects in the array may not contain required key "is_selected" then I am adding it to every object in array. But the problem is that the array is sometimes empty.
I have tried everything I could possibly find. The only way it works, is with static data.
I created sandbox also and there you can see in the console that the "COMPONENT DATA" is empty array for some reason but if you assign static objects to the array, it works flawlessly
So this is what I am doing in my child:
<template>
<ul>
<li v-for="item in items">{{item.title}}</li>
</ul>
</template>
<script>
export default {
props: {
items: {
type: Array,
default: []
}
},
data() {
return {
local_items: this.items
};
},
methods: {},
created() {
var result = this.local_items.map(function(el) {
var o = Object.assign({}, el);
o.is_selected = false;
return o;
});
this.local_items = result
console.log('COMPONENT DATA: ', this.local_items);
}
};
</script>
And this is the parent:
<template>
<test :items="items"></test>
</template>
<script>
import Test from "./Test";
import axios from 'axios'
export default {
data() {
return {
items: []
};
},
methods: {},
async created () {
try {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.items = response.data
})
}catch (e){
console.log('ERROR: ', e)
}
},
components: {
Test
}
};
</script>
What I am doing wrong? Can anyone please lead me to the right track?
Edit: if you are looking this, the working example is in the sandbox
createdlifecycle hook is called within the child component. But you can't possibly tell when the ajax call from the parent will finish and pass the data to the child. It can be before or after the created hook. So instead you want to watch your prop in the child for changes and then run your data processing.