Home > Back-end >  .map is not a function when fetching data from API reactjs
.map is not a function when fetching data from API reactjs

Time:11-24

I'm using an API to fetch data. When I console.log my data, it shows as an array. But when I try to map over it to get the data to display, it tells me that .map is not a function. I created a custom useFetch hook and then I'm importing it into a separate component. Here's my code and a screenshot of the console.log:

useFetch.js

import { useEffect, useState } from 'react'

function useFetch(url) {
    const [data, setData] = useState(null)
    const [isLoading, setIsLoading] = useState(true)
    const [error, setError] = useState(null)

    useEffect(() => {
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw Error("Sorry, couldn't fetch data for this resource!")
                }
                return response.json()
            })
            .then(responseData => {
                setData(responseData)
                setIsLoading(false)
                setError(null)
            })
            .catch(error => {
                setIsLoading(false)
                setError(error.message)
            })
    }, [url])

    return { data, isLoading, error }
}

export default useFetch

List.js

import React from 'react'
import useFetch from './useFetch'

function PrizeList2017() {
    const { data } = useFetch('http://api.nobelprize.org/v1/prize.json?year=2017&yearTo=2017')

    return (
        <div className="prize-list-2017-container">
            <h1>2017</h1>
            {data.map(prize => (
                <div key={prize.id}>
                    <h2>{prize.category}</h2>
                </div>
            ))}
            {console.log(data)}
        </div>
    )
}

export default PrizeList2017

console.log

console.log info image

Your help is greatly appreciated!

CodePudding user response:

This data is not present yep when you try to do the map so do:

  {data && data.prizes && data.prizes.map(prize => (
  • Related