Infinite loop when using a object as a prop in vue

Viewed 37

Problem: This causes the get_data() function to infinitely loop for some reason, but only when the prop is a object/dictionary, worked fine when it is just a string. This does not seem to happen when {{ this.temp }} is removed from the template.

<script setup>
    defineProps({
    city: String
    })
</script>

<template>
    <div v-if="city != null">
        {{ get_data() }}
        {{ this.temp }}
    </div>
</template>

<script>
    
    export default {
        data() {
            return {
                temp: Object
            }
        },
        methods: {
            get_data() {
                const resp = fetch("https://api.openweathermap.org/data/2.5/weather?q=" + this.city + "&appid=&units=metric");
                resp.then(response => {
                    response.json().then(obj => {
                        console.log(obj)
                        this.temp = obj
                        console.log(this.temp)
                    })
                })  
            }
        }
    }
</script>
1 Answers

I fixed this by adding a watch function to the city prop that calls the function when "city" is changed. I also added the function to mounted(). The template is also just temporary ´

<script setup>
    defineProps({
    city: String
    })
</script>

<template>
    {{ this.city }}
    {{ this.temp }}
</template>

<script>
    
    export default {
        data() {
            return {
                temp: null
            }
        },
        mounted() {
            this.get_data()
        },
        watch: {
            city: function (){
                this.get_data()
            }
        },
        methods: {
            get_data(){
                const resp = fetch("https://api.openweathermap.org/data/2.5/weather?q=" + this.city + "&appid=&units=metric");
                resp.then(response => {
                    response.json().then(obj => {
                        console.log(obj)
                        this.temp = obj
                        console.log(this.temp)
                    })
                })  
            }
        }
    }
</script>


Related