2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

I am still getting this error: Uncaught TypeError: dateRecords is undefined
The reason can be that the API returns undefined. Are you sure that it always returns an array ?
Yes, I created the API data and know for sure that an array is returned. I edited this line and it now work: let records = (await data) ?? []
I do not see any other possible reason than the data being actually undefined. Please add a console.log(records) after let records = await data; just to make sure it is not undefined

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.