setup returns courseDetail before onMounted loads data

Viewed 219

I am writing an app with vuejs and I want to load data when component is mounted but setup returns data before onMounted loads data

My Code I got the id from another component through props. then passed it through a function which contains an axios method.

The returns an array of data.

export default defineComponent({
   props: {
      courseId: {
        type: String
      }
    },
    data(){
      return {
        courseDetails: []
      }
    },

    setup(props) {
     let courseDetail = reactive([])
     let sections = reactive([])

    console.log("No details", courseDetail)
     onMounted(() => {
        // showLoader(true);

      Course.getSectionAndSubsections("get-section-and-subsections", props.courseId).then(response => {
            courseDetail = response.data.courses;
            sections = response.data.sections;
            console.log("leave my house", courseDetail)
            NotificationService.success(response.data.message);
            // showLoader(false);
        }).catch(err => {
            NotificationService.error(err.response);
            // showLoader(false);
        });
     });
     console.log("Course detail ", courseDetail);
     return{
       courseDetail
     }
    }
})

How can I solve this problem?

1 Answers

I want to load data when component is mounted but setup returns data before onMounted loads data

That's correct - before onMounted hook it should return default values. The problem is that your data is not reactive. You are using reactive like that:

let courseDetail = reactive([])
courseDetail = response.data.courses;

And that is incorrect, because you don't change couseDetail content. You assign a new object.

Probably ref would be a little better in this situation:

const courseDetail = ref([])

And then you can get value:

console.log(courseDetail.value)

and assign a new one:

courseDetail.value = SOMETHING

What you did is:

let courseDetail = reactive([])
courseDetail = response.data.courses;

It can work but it should look like this:

let state = reactive({
  courseDetail: []
})
state.courseDetail = response.data.courses;

Check my demo with two options: based on ref and based on reactive:

https://codesandbox.io/s/ref-vs-reactive-jfdvc?file=/src/App.vue

Related