React useEffect API Call Returning Undefined

31 Views Asked by At

I'm trying to make a fetch request to my backend API in React using UseEffect. But my data is undefined. When I console log my res.json(), I get a pending, fulfilled promise, so I think that means I'm on the right track.

However, after that step, it returns undefined.

Here's my error:

TypeError: Cannot read properties of undefined (reading 'map')

Here is my code. Please help!

import { useState, useEffect } from "react"
// import { useLoaderData } from "react-router-dom"
import ReactPaginate from "react-paginate"
import Record from "../components/Record"
import FieldName from "../components/FieldName"

const Index = (props) => {
    // let data = useLoaderData()

    const[data, setData] = useState([])
    useEffect(() => {
        fetch("https://backendurl.com/data", {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            }
        }).then((res) => {
            console.log(res.json())
        }).then((data) => {
            setData(data)
        }).catch((error) => console.log(error))
    })

    return <div className="records">
                {data.map((record) =>
                    <Record record={record} key={record.record_id} />
                )}
           </div>
}

export default Index
1

There are 1 best solutions below

0
an8ar On

You are trying to map the empty array. This is main problem. It is caused due to the fact that the useEffect updating the state, but the component rerenders as state has been changed. However, your useEffect runs again, and it is stuck in a cycle. You have to provide the dependency array for useEffect, and the dependancy array should be empty []. By stating like that, you are telling useEffect run only once and it will update the state only one time, after receiving fulfilled