Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
How to render a React component that relies on API data?

I am trying to render a component within a component file that relies on data from an outside API. Basically, my return in my component uses a component that is awaiting data, but I get an error of dataRecords is undefined and thus cannot be mapped over.

Hopefully my code will explain this better:

// Component.js

export const History = () => {

const [dateRecords, setDateRecords] = useState(0)
const { data, loading } = useGetRecords() // A custom hook to get the data

useEffect(() => {
  fetchData()
}, [loading, data])

const fetchData = async () => {
  try {
    let records = await data
    setDateRecords(records)
  } catch (err) {
    console.error(err)
  }
}

// Below: Render component to be used in the component return
const GameItem = ({ game }) => {
  return <div>{game.name}</div>
}

// When I map over dateRecords, I get an error that it is undefined
const renderRecords = async (GameItem) => {
  return await dateRecords.map((game, index) => (
    <GameItem key={index} game={game} />
  ))
}

const GameTable = () => {
  return <div>{renderRecords(<GameItem />)}</div>
}



return(
  // Don't display anything until dateRecords is loaded
  {dateRecords? (
    // Only display <GameTable/> if the dateRecords is not empty
    {dateRecords.length > 0 && <GameTable/>
  )
)
}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If dateRecords is meant to be an array, initialize it to an array instead of a number:

const [dateRecords, setDateRecords] = useState([]);

In this case when the API operation is being performed, anything trying to iterate over dateRecords will simply iterate over an empty array, displaying nothing.

about 4 years ago · Juan Pablo Isaza Report

0

You've set the initial state of dateRecords to 0 which is a number and is not iterable. You should set the initial state to an empty array:

const [dateRecords, setDateRecords] = useState([]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!