Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent function. My intention is to utilize these values from details to populate a component within the return function at the end.

import React from "react"
import theMovieDb from  './moviedb.js'

export default function MovieDetails(props){

    const movieDetails = GetMovieDetails(props.id)
    console.log(movieDetails)

    function GetMovieDetails(id) {
        var details = {
            genres: undefined,
            title: undefined,
            imdbID: undefined,
            popularity: undefined,
            releaseDate: undefined,
            posterPath: undefined,
        }

        theMovieDb.movies.getById({
    
            "id" : id
            
        }, function( data ) {
            data = JSON.parse( data );
            details.genres =  data.genres
            details.title =  data.original_title
            details.imdbID =  data.imdb_id
            details.popularity =  data.popularity
            details.releaseDate =  data.poster_path
            details.posterPath =  data.release_date
            console.log(details)

        }, function( err ) {
            console.error(err)
        });

        return(
            details
        );
    }

    return (
        <div className='movie-card-container'>
            <div >
                <h1>Title: {movieDetails.title}</h1>
                <h2>Year Released: 2005 </h2>
                <h2>Genre: Action/Sci-Fi</h2>
                <h3>Run Time: 2h 20m</h3>
            </div>
    
        </div>
    );
}

https://i.stack.imgur.com/iZzaW.png

Answer №1

theMovieDb.movies.getById method returns a promise, indicating that it will execute asynchronously. As a result, your GetMovieDetails function call may exit before the results are received.

A common approach is to update a state variable once the fetch operation is successfully completed.

To achieve this:

Start by creating a state variable - replace

const movieDetails = GetMovieDetails(props.id)
with

var [details, setDetails] = useState();

Then, encapsulate the data fetching in an useEffect hook (https://reactjs.org/docs/hooks-effect.html). This ensures that the data is fetched only when props.id changes, as specified in the parameter array of useEffect.

useEffect(() => GetMovieDetails(props.id), [props.id]);

Next, modify the state variable upon successful completion of the data retrieval process.

Replace

function( data ) {
        data = JSON.parse( data );
        details.genres =  data.genres
        details.title =  data.original_title
        details.imdbID =  data.imdb_id
        details.popularity =  data.popularity
        details.releaseDate =  data.poster_path
        details.posterPath =  data.release_date
        console.log(details)

    }

with

function( data ) {
        data = JSON.parse( data );
        setDetails(data)
    }

Finally, update the JSX to utilize the state variable:

return (
    <div className='movie-card-container'>
        <div >
            <h1>Title: {details?.title}</h1>
            <h2>Year Released: 2005 </h2>
            <h2>Genre: Action/Sci-Fi</h2>
            <h3>Run Time: 2h 20m</h3>
        </div>

    </div>
);

This is how it functions in essence: Upon initial component load, useEffect triggers (due to props.id) and initiates the GetMovieDetails function which creates a promise (asynchronous). Once the promise resolves successfully, the state is updated, triggering a re-render of the component where the JSX reflects the value stored in the state. Note that the initial value of the details state will be undefined unless specified otherwise during its declaration.

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

Utilizing VueJS to Establish a Binding Relationship with Props

One of my Vue components is named Avatar.vue, and it is used to create an avatar image based on user-defined props. The parameter imgType determines whether the image should have rounded corners or not. Here is the code: <template> <div> & ...

Issue with Jquery .scroll method not triggering display:none functionality

Styling Using CSS #acc-close-all, #to-top { position: relative; left: 951px; width: 29px; height: 42px; margin-bottom: 2px; display:none; } #acc-close-all a, #to-top a { position: absolute; float: right; display: block ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Tips for organizing JSON data based on personal specifications

Currently, I have a list that I am converting into a JSON String object and sending it to the UI. Gson gson = new Gson(); String jsonString = gson.toJson(environmentnamesList); return jsonString; This is the JSON object: [{"id":3272,"company_n ...

Is it possible to handle an item within a JSON as a string?

Currently, I'm tackling a Java project that involves handling JSON data structured like this: { "objectList" : [{...}, {...}, ...], "metadata" : {...} } My goal is to extract the object list and metadata as JSON strings. In essence, I ...

Converting a String into an Array using JSON

My dilemma involves converting an Array of Json elements from a String to an Object Array using Gson. Despite researching methods online, none of them seem to properly address my specific scenario. ["2": {"id": 2, "name": "Cannonball", "sp": 5, "overall_a ...

Trouble with triggering HTML5 FileReader() functions

I'm having trouble determining why neither readSuccess() nor readFailure() are being executed in the code snippet below: function readMyFile(){ var reader = new FileReader(); reader.onload = readSuccess; reader.onerror = readFailure; ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

When the HTML and PHP code keeps running, the JavaScript text on the page updates itself

I was experimenting with threading in different languages like Java, PHP, and JavaScript. I am aware that JavaScript is single-threaded and PHP lacks robust threading capabilities. Below is the code snippet I have been working on: <body> <p id= ...

I am interested in adding a personalized icon to the progress bar in Material-UI

I am currently using the MUI linerProgressBar design. I would like to incorporate a custom UI Icon that moves along with the progress. Are there any examples of this available? I have searched for one in MUI but haven't found anything. If you know of ...

Having trouble getting a React Hook to function properly in NextJS with TypeScript. Let's troubleshoot

I'm currently utilizing NextJS to showcase information fetched from a database in a table format. After retrieving the data, my intention is to leverage the map function to generate table rows and then incorporate them into the table. import React, {u ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Receiving an error message when using props in JSX prompts a syntax issue

I have a functional component that needs to only render if certain variables are not empty. I want to include the logic for determining whether the component should render directly within the component itself in order to clean up the parent component. The ...