I am developing a simple application in React, and I have an array that I want to use .map and display some options. There are two selects, one for the year, and one for the month, which should update based on the year. But when I use .map i get the “Cannot read properties of undefined” error.
I logged the array to check what was going on, and in the devtools console, the array is as expected (a two item array with an array at index 1). However, using .map or accessing the item at index 1 gets me the error.
I usually never ask stuff in stackOverflow, but this is such an unusual error that I could not understand at all what was happening.
jsx code with the log
Output of the log
Output of the log accessing item at index 1
jsx code with the log
<div>
<select name="year" value={selectedYear} onChange={(e) => {setSelectedYear(e.target.value)}}>
{
availableFolders.map((yearFolder, i) => (
<option value={yearFolder[0]} key={i}>{yearFolder[0]}</option>
))
}
</select>
{/* <select name="month">
{
availableFolders[FindIndex()][1].map((month) => (
<option value={month}>{month}</option>
))
}
</select> */}
{
console.log(availableFolders[FindIndex()])
}
</div>
Output of the log
Array(2)
0
:
"2024"
1
:
(7) ['01', '02', '03', '04', '05', '06', '07']
length
:
2
[[Prototype]]
:
Array(0)
Output of the log accessing item at index 1
Uncaught TypeError: Cannot read properties of undefined (reading '1')
at FileSelect (FileSelect.jsx:98:61)
at renderWithHooks (react-dom_client.js?v=2dcd0f01:11548:26)
at mountIndeterminateComponent (react-dom_client.js?v=2dcd0f01:14926:21)
at beginWork (react-dom_client.js?v=2dcd0f01:15914:22)
at HTMLUnknownElement.callCallback2 (react-dom_client.js?v=2dcd0f01:3674:22)
at Object.invokeGuardedCallbackDev (react-dom_client.js?v=2dcd0f01:3699:24)
at invokeGuardedCallback (react-dom_client.js?v=2dcd0f01:3733:39)
at beginWork$1 (react-dom_client.js?v=2dcd0f01:19765:15)
at performUnitOfWork (react-dom_client.js?v=2dcd0f01:19198:20)
at workLoopSync (react-dom_client.js?v=2dcd0f01:19137:13)