Pass return of a request Axios to component using props in Vuejs

Asked

Viewed 77 times

1

I’m using data from a request via Axios to popular a component form, step these values via prop for some components within this form.

The problem is that some components use the data within the created end up receiving undefined, because they are loaded before the data is received from Axios. generating some errors like this:

app.js:16258 [Vue warn]: Error in created hook: "TypeError: Cannot read property 'map' of undefined"

found in
---> <GroupsComponent> at resources/js/components/GroupsComponent.vue
       <VForm>
         <Edit> at resources/js/components/Edit.vue

I wonder if there is any way to load the component only after the data is available or something like that.

Follow the requisition code:

    created: function () {
                if(this.$route.params.data){
                     this.jsonData =  this.$route.params.data
                }else{
                     axios.get('/api/atendimentos/edit/'+this.$route.params.id)
                    .then( response =>{
                       
                         this.jsonData = response.data
                    });  
                }
        }
  • In that case, you tried something like v-if on that component so that it is rendered only when there is data in the this.jsonData? Something like <Form v-if="jsonData" />

  • The problem is that I need it to be rendered, with the v-if the component is not rendered, even after it promised to be solved, I tried to make a gambiarra by setting an empty object inside the component that presents error, so it is rendered but without the data, as a stopgap I am doing a fetch even before loading the component by Vue-router and I send the whole object as parameter, but if the user access the url directly it continues to present the same error

1 answer

0


I decided using the EventBus.$emit to pass the data to the component without the props, is not the best solution but at the moment is the best I found ;)

In the form:

 created: function () {
        if(this.$route.params.data){
             this.jsonData =  this.$route.params.data
        }else{
             axios.get('/api/atendimentos/edit/'+this.$route.params.id)
            .then( response =>{
               
                 this.jsonData = response.data
                  EventBus.$emit('atendDataLoaded', response.data)
            });  
        }

In the component:

 created: function () {
            EventBus.$on('atendDataLoaded', (data)=>{
                 this.jsonGroups = data.groups
                 this.selectedGroups = data.atend_groups.map((item) =>{
                    return item.id;
                })
            
            });
        
         },

Browser other questions tagged

You are not signed in. Login or sign up in order to post.