Home > Back-end >  How to render a React component that relies on API data?
How to render a React component that relies on API data?

Time:10-06

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/>
  )
)
}

CodePudding user response:

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.

CodePudding user response:

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([]);
  • Related