8

I have a Vue component where I am trying to get rest api (using axios) data to populate a table. The rest call returns a valid json string in chrome. However, I can't get it to populate the table in the template. When I run the view, I get the following error in the rest call:

TypeError: Cannot set property 'courses' of undefined

Here is the json being returned:

[{"CourseId":"architecture","AuthorId":"cory-house","Title":"Architecting Applications","CourseLength":"4:20","Category":"Software Architecture Test"}]

Here is my template:

<template>
  <div class="course-list-row">
    <tr v-for="course in courses">
        <td>{{ course.CourseId }}</td>
        <td>{{ course.AuthorId }}</td>
        <td>{{ course.Title }}</td>
        <td>{{ course.CourseLength }}</td>
        <td>{{ course.Category }}</td>
    </tr>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'course-list-row',
    mounted: function () {
      this.getCourses()
      console.log('mounted: got here')
    },
    data: function () {
      return {
        message: 'Course List Row',
        courses: []
      }
    },
    methods: {
      getCourses: function () {
        const url = 'https://server/CoursesWebApi/api/courses/'
        axios.get(url, {
          dataType: 'json',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          mode: 'no-cors',
          credentials: 'include'
        })
        .then(function (response) {
          console.log(JSON.stringify(response.data))
          this.courses = JSON.stringify(response.data)
        })
        .catch(function (error) {
          console.log(error)
        })
      }
    }
  }
</script>

Edit:

It appears the "this" of this.courses in the api callback function is undefined.

1 Answer 1

6

as you have edited, you have got the correct error, scope of this has changed inside axios.get, you need to make following changes:

methods: {
  getCourses: function () {
    var self = this
    const url = 'https://server/CoursesWebApi/api/courses/'
    axios.get(url, {
      dataType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      mode: 'no-cors',
      credentials: 'include'
    })
    .then(function (response) {
      console.log(JSON.stringify(response.data))
      self.courses = response.data
    })
    .catch(function (error) {
      console.log(error)
    })
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That was it! Thanks. I also had to remove the json.stringify but that was more a trail and error thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.