1

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!

1 Answer 1

1

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

  {data && data.prizes && data.prizes.map(prize => (
Sign up to request clarification or add additional context in comments.

9 Comments

Hi there! Yes, I tried that already and was still getting the same error.
i didn't see the console log, data is actually an object and data.prizes an array
Okay, I figured so but the console.log was saying array! I'm still unsure of how to extract the data from the object!
Try to map with data.prizes, it should be, i edited my message
Oh thank you so much this worked! Life saver!!!
|

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.