Is it possible to retrieve and display an object from an API using its unique ID?

I created a straightforward application. The main page displays a list of movies fetched using an API, and upon clicking on a particular movie, it leads to a new page with detailed information about that movie. On the details page, another API call is made. I modified the URL so that when the user clicks on 'More Info', it retrieves the ID of the movie object. To achieve this, I wrote a function that extracts the ID from the URL and compares it with the one obtained from the API call. If they match, the function returns true. But now I'm faced with the challenge of how to retrieve and display the movie information based on this data. What approach would you suggest? Here's the code snippet:

<template>
    <div>
        <div v-for="info in movieInfo"
            :key="info.id">

            {{info.id}}
        </div>
    </div>
</template>

<script>
import axios from 'axios'

    export default {
        name: 'ViewComp',
        data() {
            return{
                movieInfo: [],
            }
        },
        mounted () {
            axios
                .get('https://api.themoviedb.org/3/movie/popular?api_key=###&language=it-IT&page=1&include_adult=false&region=IT')
                .then(response => {
                    this.movieInfo = response.data.results
                    // console.log(response.data.results)
                })
                .catch(error => {
                    console.log(error)
                    this.errored = true
                })
                .finally(() => this.loading = false)
        },
        methods: {
            confrontID(){
                var url = window.location.href;
                var idUrl = url.substring(url.lastIndexOf('/') + 1);
                var idMovie = this.info.id;

                if (idUrl === idMovie) {
                    return true;
                }
            }
        }
        

    }

    
</script>

<style scoped lang="scss">
/*Insert component styles here*/
</style>

Answer №1

To improve efficiency, you can remove the unnecessary "return true" statement as it will automatically return true if they match. Instead, retrieve and return the movie information linked to the idUrl.

if (idUrl === idMovie) {
   return idUrl;
 }

Subsequently, utilize this information to access details about the movie.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to implement a vertical scroll bar in HTML code?

<body ng-app="myApp" ng-controller="myCtrl"> <div ng-show = "dataFromRest" ng-repeat = "x in dataFromRest.posts" > <div class="tittle" style="width: 25%;"> <a href="" ng-click="showDi ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Can I safely keep a JWT in localStorage while using ReactJS?

As I work on developing a single page application with ReactJS, one question comes to mind. I came across information indicating that using localStorage may pose security risks due to XSS vulnerabilities. However, given that React escapes all user input, ...

Beware, search for DomNode!

I attempted to create a select menu using material-ui and React const SelectLevelButton = forwardRef((props, ref) => { const [stateLevel, setStateLevel] = useState({ level: "Easy" }); const [stateMenu, setStateMenu] = useState({ isOpen ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Dynamically insert the ng-if attribute into a directive

In my code, I have implemented a directive that adds an attribute to HTML elements: module1.directive('rhVisibleFor', function ($rootScope) { return{ priority: 10000, restrict: 'A', compi ...

How to create select options in Angular.js without using the ng-option directive

I receive a JSON object from a service and I am using some of its fields to populate my select option list. However, when I try to print the selected value in my controller, the output response is "undefined". Can someone help me figure out what I'm ...

JavaScript Update Function for Pointers in Parse.com - Modify a Row with a Pointer

I am currently working with Parse and JavaScript. While I know the ObjectId from the Status_id-class, I am facing a challenge in updating the column in the Question_status-class due to it being of Pointer-type. Can anyone guide me on how to update a Poin ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Encountering difficulties while attempting to import a module in Next.js

My attempt to import the Zoom Web SDK module into my Next.js project encountered an error due to the undefined window object. Simply trying to import the websdk module resulted in this unexpected issue https://i.stack.imgur.com/NDRoC.png I am using Next ...

Assigning various variables with a single click of a button

I am attempting to perform multiple actions within a button click event using the Vuetify framework: <v-btn flat color="indigo darken-3" @click.stop="dialogDelete = true; deleteTemporaryId = offer.id">Delete</v-btn> However, it appears that ...

Auto-populate AngularJS form using PHP array via JSON and $http

I came across a fantastic autocomplete feature in this plunker that I need to replicate using a PHP array with $http. When I tried adding an alert to check my array, it worked perfectly. However, I'm stuck on how to implement the filter in AngularJS. ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

Tips for generating a single sitemap in Next.js

Utilizing the next-sitemap package to generate a sitemap, I have both dynamic and static pages. This is what my next-sitemap.config.js file looks like: module.exports = { siteUrl: 'https://example.com', generateRobotsTxt: false, excl ...

Creating dynamic components in vue-router based on route parameters

Is it possible to dynamically use components in Vue based on the value of a route parameter? For instance, let's say we have the following scenario: path: '/model/:modelName', components: { default: ModelDefinition.models.find((model) =& ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...