I'm trying to display years when the input is changed to 'years' using State, but I'm having an issue.
const handleChange = (e, countMonth,countYear) =>{
if(e.target.value === 'months'){
setMonths(countMonth)
} else if( e.target.value === 'year'){
setMonths(countYear)
}
}
I'm trying to display different data when year is clicked with this map method:
<tbody>
{
months.map(({ date, count }, index) => (
<tr key={index}>
<td>{date}</td>
<td>{count}</td>
</tr>
))}
</tbody>
I keep getting the error 'TypeError: Cannot read property 'map' of undefined'
Here is the full sandbox code: https://codesandbox.io/s/wizardly-clarke-szge3?file=/src/data.js
In your sandbox code, I tried putting console logs, found that
countYear
isundefined
and that's is being set tomonths
.Ideally you should validate
countYear
before its being set to statemonths
[else if( e.target.value === 'year' && countYear)
] or fix the root cause whycountYear
isundefined