0

I am trying to fetch data from different 2 json.

json for data1: [{ id: 1, name: 'abc'},{id:2, name: 'def'}] json for data2: [{ product_id: 0001, },{product_id:0002}]

By using these I would like to create this kind of structure.

myStore = [ { id: 1, name: 'abc', products: [{ product_id: 0001, },{product_id:0002}]}, { id: 2, name: 'def', products: [{ product_id: 0003, },{product_id:0004}]}

<script>
  export default {
    data: () => ({
        myStore: [],
        isLoaded: false,
    }),
    created(){
        this.fetchData()
    },
    watch: {
    '$route': 'fetchData'
    },
    methods: {
        fetchData() {
            axios.get('api/data1')
                .then(response => {
                    this.myStore = response.data
                })
                .catch(error => {
                    console.log(error);
                })
                .then(() => {
                    this.myStore.forEach(subStore => {                    
                        axios.get('api/data2?substore_id=' + subStore.id)
                            .then(response => {
                                this.myStore.products = response.data
                            })
                            .catch(error => {
                                console.log(error);
                            })
                    });
                })
                this.isLoaded = true;
        },
    }, 
  }

I checked console.log, the structure that I want to have is created correctly however the problem is about rendering. I tried to render {{myStore}}, I can only see the first data (data1) results [{ id: 1, name: 'abc'},{id:2, name: 'def'}] When I update any code without reload page (via F5), vue updates this change. This time I can see the structure correctly that I wanna have. But when I reload page all is gone.

Caner Sezgin
  • 328
  • 3
  • 16
  • Not sure if this is the issue, but your 'this.isLoaded = true;' should probably be in your .then() statement - just move it up one line to inside the '})' - otherwise, since axios is asynchronous, isLoaded will be set to true before the store is fully loaded. – Jayem163 Oct 25 '18 at 15:28
  • But even then it won't wait for the data2 load loop to end... – Jayem163 Oct 25 '18 at 15:30
  • I got it, you are right but the main problem is this. I would like to render after data1 and data2 are successfully fetched. However now, data1 is fetched, rendered then data2 is loaded. – Caner Sezgin Oct 25 '18 at 17:12
  • I think the best way is to use the "forEach" optional 3rd parameter (the array itself). Then set a variable to detect array.length and only set and set loading as finished when it reaches the end. check: https://stackoverflow.com/questions/18983138/callback-after-all-asynchronous-foreach-callbacks-are-completed – Jayem163 Oct 25 '18 at 17:59

0 Answers0