0

I'm fetching data from an API. One of the values in the data is an array called results. I'm mapping through this array to create a list of IDs, but the list is not appearing.

The data (I've just included the first 2 items in the results array but there are many more):

{
  "page": 1,
  "total_results": 10000,
  "total_pages": 500,
  "results": [
    {
      "popularity": 176.614,
      "vote_count": 3845,
      "video": false,
      "poster_path": "/xBHvZcjRiWyobQ9kxBhO6B2dtRI.jpg",
      "id": 419704,
      "adult": false,
      "backdrop_path": "/t4z8OlOEzH7J1JRFUN3rcm6XHNL.jpg",
      "original_language": "en",
      "original_title": "Ad Astra",
      "genre_ids": [
        18,
        878
      ],
      "title": "Ad Astra",
      "vote_average": 6.1,
      "overview": "The near future, a time when both hope and hardships drive humanity to look to the stars and beyond. While a mysterious phenomenon menaces to destroy life on planet Earth, astronaut Roy McBride undertakes a mission across the immensity of space and its many perils to uncover the truth about a lost expedition that decades before boldly faced emptiness and silence in search of the unknown.",
      "release_date": "2019-09-17"
    },
    {
      "popularity": 138.944,
      "vote_count": 255,
      "video": false,
      "poster_path": "/9zrbgYyFvwH8sy5mv9eT25xsAzL.jpg",
      "id": 531454,
      "adult": false,
      "backdrop_path": "/jMO1icztaUUEUApdAQx0cZOt7b8.jpg",
      "original_language": "en",
      "original_title": "Eurovision Song Contest: The Story of Fire Saga",
      "genre_ids": [
        35,
        10402
      ],
      "title": "Eurovision Song Contest: The Story of Fire Saga",
      "vote_average": 6.6,
      "overview": "Two small-town aspiring musicians chase their pop star dreams at a global music competition, where high stakes, scheming rivals and onstage mishaps test their bond.",
      "release_date": "2020-06-26"
    },
    .....
  ]
}

My code:

fetch(url).then((res) => res.json())
            .then((data) => {
                const listItems = data.results.map((movie) =>
                    <li key={movie.id} >
                        {movie.id.toString()}
                    </li>
                );
                return (
                    <ul>{listItems}</ul>
                );
            })    
            .catch(error => {
                console.log("Error fetching data", error);
            });

If I console.log(movie.id), it prints it to the console, so it seems it's finding the data with no problem, but the page still appears blank.

0

2 Answers 2

1

The fetch code makes not sense, since you cannot render your list in the promise body.

You have to save data in the state and then map the state in the template of the component.

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

function YourComponent() {
  const [listItems, setListItems] = useState([]);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        setListItems(data.results);
      })
      .catch((error) => {
        console.log("Error fetching data", error);
      });
  }, []);

  return (
    <ul>
      {listItems.map((movie) => (
        <li key={movie.id}>{movie.id.toString()}</li>
      ))}
    </ul>
  );
}

export default YourComponent;
Sign up to request clarification or add additional context in comments.

Comments

1

You should do something below to show the page:

  • Save the listItems to the state.
  • After fetch, call setState to update listItems.
  • Use listItems in render function.

That mean, in your above code, the return statement inside then does not have any effect to render in React. You need to to use state to trigger re-render.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.