1

I have the function below from: https://github.com/anaida07/MEVN-boilerplate/blob/master/client/src/components/EditPost.vue

methods: {
  async getPost () {
    const response = await PostsService.getPost({
      id: this.$route.params.id
    })
    this.title = response.data.title
    this.description = response.data.description
  // this.$router.push({ name: 'Posts' })
},

I am learning about MEVN. I wanted to know if there was anyway to write the same function without using async/await. I currently have come up with the following:

methods: {
  getPost () {
    const response = PostsService
    .getPost({
      id: this.$route.params.id
    })
    this.title = response.data.title
    this.description = response.data.description

   //this.$router.push({ name: 'Posts' })
},

But I am getting an error in my console log saying: Error in mounted hook: "TypeError: response.data is undefined". Any help would be greatly appreciated.

2
  • Is the a reason why you don't want async-await syntax? Commented Jun 25, 2018 at 20:58
  • it doesn't work with my version of webpack for some reason Commented Jun 27, 2018 at 19:19

1 Answer 1

1

It looks like PostsService extends axios, so you can use it as a promise:

methods: {
  getPost () {
    PostsService
      .getPost({
        id: this.$route.params.id
      })
      .then(({data}) => {
        this.title = data.title
        this.description = data.description
        this.$router.push({ name: 'Posts' })
      }

},

The reason for your error was that response = PostsService.getPosts() doesn't actually populate the response variable with the data. It has to run the query first, then you can access it in the callback in .then()

Sign up to request clarification or add additional context in comments.

2 Comments

I agree with Jeff. The response is undefined since the PostsService.getPost() is an asynchronous request and you will have to wait for it to resolve (or reject) before accessing the response contents. For the errors thrown by this request, you can just catch them using a catch() block after the then() case.
Thank you, this was a quick fix!

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.