Home > Enterprise >  How to fix error when trying to render a list
How to fix error when trying to render a list

Time:04-27

I'm trying to render a list of movies, but the following error happens: "data.map is not a function". Although the API return is an array of objects.

API: enter link api

hook useRequestData:

  import { useEffect, useState } from "react"
import axios from "axios"

export function useRequestData<T = unknown>(url: string) {
    const [data, setData] = useState<T | null>(null)

    useEffect(() => {
        axios.get(url)
            .then(response => {
                setData(response.data)
            })
    }, [])

    return { data }
}
  import { useRequestData } from "../../hooks/useRequestData"
import { baseUrl } from "../../services/api"

import { Container } from "./style"
import movieImg from "../../assets/movie.svg"

type Films = {
    id: number;
    backdrop_path: string;
    title: string;
    release_date: string;
}

export const MovieCard = () => {
    const { data } = useRequestData<Films[]>(baseUrl)
    console.log(data)


    return (
        <>
            {data?.map((films) => (
                <Container key={films.id}>
                    <img src={films.backdrop_path} alt="" />
                    <h3>{films.title}</h3>
                    <p>12 NOV 2021</p>
                </Container>
            ))}
        </>
    )
}

CodePudding user response:

According to the API docs, your data will be an object that contains a results array.

Try data?.results.map instead of data?.map.

CodePudding user response:

According to the API response return object. That means

    response data = {
    "page": 1,
    "results": [
    {
      "poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
      "adult": false,
      "overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
      "release_date": "2016-08-03",
      "genre_ids": [
        14,
        28,
        80
      ],
      "id": 297761,
      "original_title": "Suicide Squad",
      "original_language": "en",
      "title": "Suicide Squad",
      "backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
      "popularity": 48.261451,
      "vote_count": 1466,
      "video": false,
      "vote_average": 5.91
    }
  ]
}

To access the results, use setData(response.data?.results) to set the value for data in your state if you only need result[] to MovieCard Component. If you want whole response for the MovieCard, set the state as you did and when access the array do like this.

return (
    <>
        {data?.results.map((films) => (
            <Container key={films.id}>
                <img src={films.backdrop_path} alt="" />
                <h3>{films.title}</h3>
                <p>12 NOV 2021</p>
            </Container>
        ))}
    </>
)
}
  • Related