[Vuejs]-Vue method return undefined when used in other method

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

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.

Leave a comment