Axios get request and display results to html with vue

Viewed 38

Currently learning Vue and Axios, and i'm trying to get data from an API and display it within an HTML card, but it seems that it tries to display the data before getting it from the API and then nothing renders.

<script type="text/javascript">
        const {createApp} = Vue;
        const data = null;
        const error = null;
        
        const app = createApp({
            data(){
                return{
                    movieID: localStorage.getItem("movieID"),
                    movieDetail: null
                }
            },
            methods:{
                getMovieDetail(){
                    var config = {
                    method: 'get',
                    url: 'https://api.themoviedb.org/3/movie/'+localStorage.getItem("movieID"),
                    headers: { 
                        'Authorization': 'Bearer'
                    }
                    };

                    axios(config);
                    app.movieDetail = respuesta.data;
                    document.getElementById("tituloPeli").innerHTML = app.movieDetail.title
                    .then(function (response) {
                        app.movieDetail = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                }
            },
            mounted(){
                this.getMovieDetail();
            }
        }).mount("#contenedor");

    </script>
<div id="contenedor">
        <div class="container-xxl my-4">
            <h1>Data from movie with ID {{movieID}}</h1>
        </div>

        <div class="container">
            <div class="row align-items-start">
                <div class="col-12">
                    <div class="card my-2">
                        <img class="card-img-top" :src="'https://image.tmdb.org/t/p/w600_and_h900_bestv2' + movieDetail.poster_path">
                        <div class="card-body">
                            <h6 class="card-title">
                                {{movieDetail.title}}
                            </h6>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

Highly appreciated if you could help me, thank u so much

1 Answers

The key is to not render the data until it's ready. This is called conditional rendering and can be done using the v-if directive

<h6 v-if="movieDetail?.title" class="card-title">
    {{movieDetail.title}}
</h6>

Along with standard javascript optional chaining you can guarantee an object and it's properties are all defined before rendering it in your template.

Related