简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM