Keep getting 'map of undefined' when displaying table data, React hooks

124 views Asked by At

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

1

There are 1 answers

2
Pavan On

In your sandbox code, I tried putting console logs, found that countYear is undefined and that's is being set to months.

Ideally you should validate countYear before its being set to state months [else if( e.target.value === 'year' && countYear)] or fix the root cause why countYear is undefined

const handleChange = (e, countMonth,countYear) =>{
      
  if(e.target.value === 'months'){
    console.log('countMonth ', countMonth)
    setMonths(countMonth)

  } else if( e.target.value === 'year'){
    console.log('countYear ', countYear)
    setMonths(countYear)
  
  }
}