Home > Back-end >  Vue.JS - Api request - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading
Vue.JS - Api request - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading

Time:05-31

<template>

    <article >
        <div >
            <span>Code Quotes</span>
        </div>
        <div >
                <span v-html="fetchedQuotes.data.quote"></span>
                <span>{{fetchedQuotes.data.author}}</span> 
        </div>
    </article>

</template>

<script>
    export default {
        data(){
            return {
               
                fetchedQuotes: [],
                contentUrl: "https://apiurl.tld/"
            };
        },
        mounted() {
            this.getQuotes(this.contentUrl, "quotes");
            
        },
        methods: {
            async getQuotes(url, collection) {
                try {
                    
                    let response = await fetch(url   collection "/" Math.ceil(Math.random()*6));
                    this.fetchedQuotes = await response.json();
                } catch (error) {
                    console.log(error);
                }
            }
        }
    };
</script>

I am trying to randomly fetch quotes from a Directus project API. But this code keeps giving me the error :

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'quote').

I have tried several different solutions but now I am stuck and need help figuring out what's preventing this code from working.

Any help will be appreciated.

CodePudding user response:

The problem is, you are trying to access fetchedQuotes.data.quote before its being fetched. To handle this, check if your fetchedQuotes is not empty in your html tag

<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>
  • Related