Home > Mobile >  ReactJs json map returning undefined after loading
ReactJs json map returning undefined after loading

Time:03-25

So I'm fetching an API call which I'm then trying to iterate over in order to display as a list. My code so far is:

import React, { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [trendingMovies, setTrendingMovies] = useState();

  useEffect(() => {
    fetch(
      "https://api.themoviedb.org/3/trending/all/day?api_key=***"
    )
      .then((res) => res.json())
      .then((results) => console.log(results))
      .then((data) => setTrendingMovies(data))
      .catch((error) => console.log(error))
      .then(setIsLoading(false));
  }, [trendingMovies]);

  function Loading() {
    return <h1>Loading...</h1>;
  }

  function DisplayTrendingMovies() {
    return (
      <>
        <p>Trending:</p>
        {console.log(trendingMovies)}
        <ul>
          {trendingMovies &&
            trendingMovies.map((movie) => (
              <li key={movie.results}>{movie.results.original_title}</li>
            ))}
        </ul>
      </>
    );
  }

  return <>{isLoading ? Loading() : DisplayTrendingMovies()}</>;
}

export default App;

And in fact, the json loads, a sample call is:

  {"page": 1,
  "results": [
    {
      "genre_ids": [28, 12, 878],
      "original_language": "en",
      "original_title": "Spider-Man: No Way Home",
      "poster_path": "/1g0dhYtq4irTY1GPXvft6k4YLjm.jpg",
      "video": false,
      "vote_average": 8.2,
      "vote_count": 9831,
      "overview": "Peter Parker is unmasked and no longer able to separate his normal life from the high-stakes of being a super-hero. When he asks for help from Doctor Strange the stakes become even more dangerous, forcing him to discover what it truly means to be Spider-Man.",
      "release_date": "2021-12-15",
      "title": "Spider-Man: No Way Home",
      "id": 634649,
      "adult": false,
      "backdrop_path": "/iQFcwSGbZXMkeyKrxbPnwnRo5fl.jpg",
      "popularity": 9675.798,
      "media_type": "movie"
    },
    {
      "adult": false,
      "backdrop_path": "/qswImgf57wBf2i8Fv6K2O2BdMoe.jpg",
      "genre_ids": [53, 10749, 18],
      "id": 619979,
      "original_language": "en",
      "original_title": "Deep Water",
      "overview": "Vic and Melinda Van Allen are a couple in the small town of Little Wesley. Their loveless marriage is held together only by a precarious arrangement whereby, in order to avoid the messiness of divorce, Melinda is allowed to take any number of lovers as long as she does not desert her family.",
      "poster_path": "/6yRMyWwjuhKg6IU66uiZIGhaSc8.jpg",
      "release_date": "2022-03-18",
      "title": "Deep Water",
      "video": false,
      "vote_average": 6.0,
      "vote_count": 1,
      "popularity": 111.471,
      "media_type": "movie"
    },
    {
      "genre_ids": [28, 53],
      "original_language": "sv",
      "original_title": "Svart krabba",
      "poster_path": "/mcIYHZYwUbvhvUt8Lb5nENJ7AlX.jpg",
      "id": 760868,
      "vote_average": 0.0,
      "overview": "To end an apocalyptic war and save her daughter, a reluctant soldier embarks on a desperate mission to cross a frozen sea carrying a top-secret cargo.",
      "release_date": "2022-03-18",
      "vote_count": 0,
      "video": false,
      "adult": false,
      "backdrop_path": "/w8pSD1jVt2OzBCr8QQTTjk0mBHt.jpg",
      "title": "Black Crab",
      "popularity": 41.066,
      "media_type": "movie"
    },
    {
      "genre_ids": [16, 10751, 35, 14],
      "original_language": "en",
      "original_title": "Turning Red",
      "poster_path": "/qsdjk9oAKSQMWs0Vt5Pyfh6O4GZ.jpg",
      "video": false,
      "vote_average": 7.4,
      "vote_count": 565,
      "overview": "Thirteen-year-old Mei is experiencing the awkwardness of being a teenager with a twist – when she gets too excited, she transforms into a giant red panda.",
      "release_date": "2022-03-10",
      "title": "Turning Red",
      "id": 508947,
      "adult": false,
      "backdrop_path": "/iPhDToxFzREctUA0ZQiYZamXsMy.jpg",
      "popularity": 7663.359,
      "media_type": "movie"
    },
    {
      "video": false,
      "vote_average": 6.0,
      "overview": "At an elite New England university built on the site of a Salem-era gallows hill, three black women strive to find their place. Navigating politics and privilege, they encounter increasingly terrifying manifestations of the school's haunted past… and present.",
      "release_date": "2022-03-18",
      "vote_count": 1,
      "adult": false,
      "backdrop_path": "/bW0zTTdvc9zafc6hDEG1pMDuMCW.jpg",
      "title": "Master",
      "genre_ids": [27, 53, 18, 9648],
      "id": 680829,
      "original_language": "en",
      "original_title": "Master",
      "poster_path": "/gxbwRHsQ2v6DQv28ttp7pIx7Utj.jpg",
      "popularity": 37.859,
      "media_type": "movie"
    },
    {
      "id": 850018,
      "poster_path": "/r3eGUCijDCNqwcP1Ri8AZyTbPzI.jpg",
      "video": false,
      "vote_average": 0.0,
      "overview": "A man breaks into a tech billionaire's empty vacation home, but things go sideways when the arrogant mogul and his wife arrive for a last-minute getaway.",
      "release_date": "2022-03-11",
      "vote_count": 0,
      "adult": false,
      "backdrop_path": "/cc7Nmid20lcfNh1eucWdLKidi7s.jpg",
      "title": "Windfall",
      "genre_ids": [80, 18, 53],
      "original_title": "Windfall",
      "original_language": "en",
      "popularity": 12.777,
      "media_type": "movie"
    },
    {
      "id": 691683,
      "video": false,
      "title": "Cheaper by the Dozen",
      "overview": "This remake of the beloved classic follows the raucous exploits of a blended family of 12, the Bakers, as they navigate a hectic home life while simultaneously managing their family business.",
      "release_date": "2022-03-18",
      "vote_count": 1,
      "adult": false,
      "backdrop_path": "/4YOpxmGyQZFELwLB7JqcpYKnmKw.jpg",
      "vote_average": 10.0,
      "genre_ids": [35, 10751, 18],
      "poster_path": "/qNRsouZh5zmhaE3n4QpLDXzy1gQ.jpg",
      "original_language": "en",
      "original_title": "Cheaper by the Dozen",
      "popularity": 43.263,
      "media_type": "movie"
    },
    {
      "title": "The Adam Project",
      "overview": "After accidentally crash-landing in 2022, time-traveling fighter pilot Adam Reed teams up with his 12-year-old self on a mission to save the future.",
      "release_date": "2022-03-11",
      "adult": false,
      "backdrop_path": "/ewUqXnwiRLhgmGhuksOdLgh49Ch.jpg",
      "genre_ids": [878, 12, 35],
      "vote_count": 705,
      "original_language": "en",
      "original_title": "The Adam Project",
      "poster_path": "/wFjboE0aFZNbVOF05fzrka9Fqyx.jpg",
      "video": false,
      "id": 696806,
      "vote_average": 7.0,
      "popularity": 2137.891,
      "media_type": "movie"
    },
    {
      "adult": false,
      "backdrop_path": "/zQG1FYDqoWo2hYhE5GVZ1yrWSfh.jpg",
      "genre_ids": [10751, 18],
      "id": 921655,
      "original_language": "en",
      "original_title": "Rescued by Ruby",
      "overview": "Chasing his dream to join an elite K-9 unit, a state trooper partners with a fellow underdog: clever but naughty shelter pup Ruby. Based on a true story.",
      "poster_path": "/tPlJEodEn0SSV4avo8KSawtlTlN.jpg",
      "release_date": "2022-03-17",
      "title": "Rescued by Ruby",
      "video": false,
      "vote_average": 7.4,
      "vote_count": 6,
      "popularity": 47.237,
      "media_type": "movie"
    },
    {
      "overview": "In his second year of fighting crime, Batman uncovers corruption in Gotham City that connects to his own family while facing a serial killer known as the Riddler.",
      "release_date": "2022-03-01",
      "adult": false,
      "backdrop_path": "/5P8SmMzSNYikXpxil6BYzJ16611.jpg",
      "id": 414906,
      "genre_ids": [80, 9648, 53],
      "original_language": "en",
      "original_title": "The Batman",
      "poster_path": "/74xTEgt7R36Fpooo50r9T25onhq.jpg",
      "vote_count": 1981,
      "video": false,
      "vote_average": 8.0,
      "title": "The Batman",
      "popularity": 2675.235,
      "media_type": "movie"
    },
    {
      "release_date": "2022-03-17",
      "adult": false,
      "backdrop_path": "/trtFAmf4IcndxSh5tIfLwxPyW67.jpg",
      "genre_ids": [28, 53],
      "vote_count": 4,
      "original_language": "en",
      "original_title": "Panama",
      "poster_path": "/82I3tDsGDTMy7lHar84Gz0jUuyW.jpg",
      "title": "Panama",
      "video": false,
      "vote_average": 6.0,
      "id": 628878,
      "overview": "An ex-marine is hired by a defense contractor to travel to Panama to complete an arms deal. In the process he becomes involved with the U.S. invasion of Panama, and learns an important lesson about the true nature of political power.",
      "popularity": 40.113,
      "media_type": "movie"
    },
    {
      "backdrop_path": "/fUjATGfykF0EU57DhMDkIXqQlc5.jpg",
      "first_air_date": "2022-03-17",
      "genre_ids": [18, 10765],
      "id": 113566,
      "name": "DMZ",
      "origin_country": ["US"],
      "original_language": "en",
      "original_name": "DMZ",
      "overview": "In the near future after a bitter civil war leaves Manhattan a demilitarized zone (DMZ), destroyed and isolated from the rest of the world, fierce medic Alma Ortega sets out on a harrowing journey to find the son she lost in the evacuation of New York City at the onset of the conflict. Standing in her way are gangs, militias, demagogues and warlords, including Parco Delgado, the popular — and deadly — leader of one of the most powerful gangs in the DMZ.",
      "poster_path": "/wnug9DhsenurS5dWCypjZSRFnH6.jpg",
      "vote_average": 10.0,
      "vote_count": 3,
      "popularity": 66.357,
      "media_type": "tv"
    },
    {
      "backdrop_path": "/x8KTttToqfHC92JiD2Cs8WWkBG7.jpg",
      "genre_ids": [18],
      "original_language": "en",
      "poster_path": "/rFlYeo84b5YtzNkN0IonN6ZCPic.jpg",
      "first_air_date": "2022-03-17",
      "vote_average": 0.0,
      "original_name": "WeCrashed",
      "origin_country": ["US"],
      "vote_count": 0,
      "overview": "Inspired by actual events — and the love story at the center of it all. WeWork grew from a single coworking space into a global brand worth $47 billion in under a decade. Then, in less than a year, its valuation dropped $40 billion. What happened?",
      "id": 117821,
      "name": "WeCrashed",
      "popularity": 61.183,
      "media_type": "tv"
    },
    {
      "vote_average": 7.1,
      "title": "Nightmare Alley",
      "overview": "An ambitious carnival man with a talent for manipulating people with a few well-chosen words hooks up with a female psychiatrist who is even more dangerous than he is.",
      "release_date": "2021-12-02",
      "id": 597208,
      "adult": false,
      "backdrop_path": "/g0YNGpmlXsgHfhGnJz3c5uyzZ1B.jpg",
      "genre_ids": [80, 18, 53],
      "original_language": "en",
      "original_title": "Nightmare Alley",
      "poster_path": "/vfn1feL0V9HNSXuLLpaxAW8O6LO.jpg",
      "vote_count": 1055,
      "video": false,
      "popularity": 1099.529,
      "media_type": "movie"
    },
    {
      "genre_ids": [18, 35],
      "original_language": "en",
      "original_title": "Dog",
      "poster_path": "/zHQy4h36WwuCetKS7C3wcT1hkgA.jpg",
      "id": 626735,
      "vote_average": 7.6,
      "overview": "An army ranger and his dog embark on a road trip along the Pacific Coast Highway to attend a friend's funeral.",
      "release_date": "2022-02-17",
      "vote_count": 110,
      "video": false,
      "adult": false,
      "backdrop_path": "/8T7SS4jU7TmtqrUr45JgZASCTUP.jpg",
      "title": "Dog",
      "popularity": 200.167,
      "media_type": "movie"
    },
    {
      "adult": false,
      "backdrop_path": "/zOVxbbt8BrrjWBJ0eO21S2adUvo.jpg",
      "genre_ids": [35],
      "id": 776328,
      "original_language": "it",
      "original_title": "Marilyn ha gli occhi neri",
      "overview": "Clara and Diego, under the guidance of the psychiatrist of a day rehabilitation center for disturbed people who attend, decide to transform the treatment center into a restaurant, involving all their other companions.",
      "poster_path": "/thHmfbg56EDMCTmjEuz6Xo5M8hV.jpg",
      "release_date": "2021-10-14",
      "title": "Marilyn's Eyes",
      "video": false,
      "vote_average": 6.9,
      "vote_count": 136,
      "popularity": 29.106,
      "media_type": "movie"
    },
    {
      "id": 93544,
      "overview": "Two seasoned drug dealers return to the gritty street of London, but their pursuit of money and power is threatened by a young and ruthless hustler.",
      "name": "Top Boy",
      "vote_count": 14,
      "vote_average": 8.9,
      "backdrop_path": "/4CqfqazO2EBhN469XfIp7RSJZ7h.jpg",
      "original_language": "en",
      "genre_ids": [80, 18],
      "first_air_date": "2019-09-13",
      "original_name": "Top Boy",
      "origin_country": [],
      "poster_path": "/mGZpOEaLZTRzWeQMq5SZM5BbDZg.jpg",
      "popularity": 66.767,
      "media_type": "tv"
    },
    {
      "backdrop_path": "/3vOh84wLx47L1vhNTUuf1Z0zv2i.jpg",
      "genre_ids": [10765],
      "original_language": "pl",
      "poster_path": "/bBzkreVliFn18zFBjysanZnC3Yq.jpg",
      "first_air_date": "2022-03-18",
      "vote_average": 0.0,
      "original_name": "Krakowskie potwory",
      "origin_country": ["PL"],
      "vote_count": 0,
      "overview": "A young woman haunted by her past joins a mysterious professor and his group of gifted students who investigate paranormal activity — and fight demons.",
      "id": 158396,
      "name": "Cracow Monsters",
      "popularity": 24.704,
      "media_type": "tv"
    },
    {
      "backdrop_path": "/ifUfE79O1raUwbaQRIB7XnFz5ZC.jpg",
      "genre_ids": [27, 9648, 53],
      "original_language": "en",
      "original_title": "Scream",
      "poster_path": "/kZNHR1upJKF3eTzdgl5V8s8a4C3.jpg",
      "video": false,
      "vote_average": 6.8,
      "vote_count": 937,
      "overview": "Twenty-five years after a streak of brutal murders shocked the quiet town of Woodsboro, a new killer has donned the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town’s deadly past.",
      "release_date": "2022-01-12",
      "id": 646385,
      "title": "Scream",
      "adult": false,
      "popularity": 1191.305,
      "media_type": "movie"
    },
    {
      "original_language": "en",
      "original_title": "Loveland",
      "poster_path": "/zVxFQG0rAFITjIygEMHFRLtR6JI.jpg",
      "video": false,
      "id": 659924,
      "release_date": "2022-03-17",
      "vote_count": 0,
      "adult": false,
      "backdrop_path": "/2QerJOQmmWcINcM1S1sNkDxjXkj.jpg",
      "genre_ids": [878, 10749, 53],
      "vote_average": 0.0,
      "overview": "In an uncharted future, two hardened souls meet and confront each other with the things they have done and what they have become.",
      "title": "Loveland",
      "popularity": 32.544,
      "media_type": "movie"
    }
  ],
  "total_pages": 1000,
  "total_results": 20000
}

But I never get the iterating ul elements. I think this is somehow related to how I'm running my useEffect, because in logs I get undefined before the json call is completed, the correct json (although it doesn't iterate/display as ul elements) and then another undefined.

Any pointers?

CodePudding user response:

I think the problem is with the way fetch api's promise is handled. .then((results) => console.log(results)) seems to return undefined and the following .then is receiving data as undefined. Please try like below and let me know if it works!

    import React, { useState, useEffect } from "react";

function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [trendingMovies, setTrendingMovies] = useState();

  useEffect(() => {
    fetch(
      "https://api.themoviedb.org/3/trending/all/day?api_key=***"
    )
      .then((res) => res.json())
      .then((data) => setTrendingMovies(data.results))
      .catch((error) => console.log(error))
      .then(setIsLoading(false));
  }, []);

  function Loading() {
    return <h1>Loading...</h1>;
  }

  function DisplayTrendingMovies() {
    return (
      <>
        <p>Trending:</p>
        {console.log(trendingMovies)}
        <ul>
          {trendingMovies &&
            trendingMovies.map((movie) => (
              <li key={movie.name}>{movie.original_title}</li>
            ))}
        </ul>
      </>
    );
  }

  return <>{isLoading ? Loading() : DisplayTrendingMovies()}</>;
}

export default App;

enter image description here

CodePudding user response:

Try this:

  useEffect(() => {           
          fetch("https://api.themoviedb.org/3/trending/all/day?api_key=***")
                .then((data) => data.json())
                .then((data) => setTrendingMovies(data))
                .catch((err) => console.log(err));
                .then(setIsLoading(false));

  }, []);
{trendingMovies?.results?.map((movie) => (
              <li key={movie.results}>{movie.results.original_title}</li>
            ))}

The question mark allows the component to wait until trendingMovies array has data.

  • Related