0

I am trying to fetch replies of a comment in an object. From the backend,i.e,LARAVEL I receive 1 object. But, in Vue it becomes undefined

Method

fetchReplies(commentid) {
  axios
    .get("/reply/" + commentid)
    .then(res => {
      if (res.data != null) {
        console.log(res.data);
        return res.data;
      }
    })
    .catch(function(err) {
      console.log(err);
    });
}

OutPut

(2) [{…}, {…}] // for commentid 42

But When used this method in some other method

fetchComments() {
  var boardid = this.boardid;
  axios
    .get("/comment/" + boardid)
    .then(res => {
      if (res.data != null) {
        this.comments = res.data;
           console.log(this.fetchReplies(42));
        }

    })
    .catch(function(err) {
      console.log(err);
    });
},

OutPut

Undefined

Before a while, when i fetch in Vue, I receive 1 object containing data and one with no data. But, suddenly that object with no data disappears.

2 Answers2

0

Axios is an asynchronous call, so it seems console.log is called before the fetch call has returned. The most convenient way to use axios call it with es2017 async/await.

Jeremy Walters
  • 2,081
  • 16
  • 28
0

Your console.log(this.fetchReplies(42)); is calling a function which is still running as axios in asynchronous

If you make your fetchComments an async function, you can wait until your fetchReplies is finished before logging something.

Added a code snippet, make sure axios is returning something as well.

let results = await this.fetchReplies(42)
console.log(results)

const URL = 'https://jsonplaceholder.typicode.com/posts';
    new Vue({
        el: "#app",
        data: {
            comments : '',
            replies : ''
        },
        methods: {
            fetchReplies(id) {
                return new Promise((resolve, reject) => {
                    axios
                        .get(URL)
                        .then(res => {
                            if (res.data != null) {
                                resolve(res.data)
                            } else {
                                reject('RejectReason')
                            }

                        })
                        .catch(function (err) {
                            console.log(err);
                            reject(err)
                        });
                })
            },
            async fetchComments() {
                axios
                    .get(URL)
                    .then(async res => {
                        if (res.data != null) {
                            //Result from comments is in
                            this.comments = res.data;
                            let replies = await this.fetchReplies(1);
                            this.replies = replies;
                        }
                    })
                    .catch(function (err) {
                        console.log(err);
                    });
            }
        }
    })
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <button @click="fetchComments()">
        Some text
    </button>
    <h1>Comments</h1>
    {{comments}}
    <h2>Replies</h2>
    {{replies}}
</div>

Update: Change snippet to change data visibly in template

Cübe
  • 71
  • 4
  • Still the same result –  Jan 07 '19 at 08:28
  • i am still getting undefined –  Jan 07 '19 at 10:00
  • Hey man, thanks a lot, thankyou so much.. That worked amazingly... I had made some mistake earlier but the snippet solved the problem.. thanks buddy –  Jan 07 '19 at 19:11
  • But this is not working in template. I'm getting whole data in vue, but unable to access in template –  Jan 08 '19 at 03:22
  • @Qwerty Could you elaborate? you want to want to use the Axios results in your template I guess? To do that you first need to set a data attribute, which you can update in your methods. – Cübe Jan 08 '19 at 07:06
  • Exactly, By this I did got data in my Vue, but when i try to use it in template, it says it's undefined –  Jan 08 '19 at 14:08
  • @Qwerty I changed the snippet. Basically, you define your template variables first and the page is just an empty string. If you click the button both functions run and update your template vars. If you want functions to run on page load, please look at The Vue Instance Lifecycle https://vuejs.org/v2/guide/instance.html – Cübe Jan 08 '19 at 17:49