0

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

Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
Shuib Abdillahi
  • 119
  • 1
  • 10
  • 2
    Here's how you're calling `handleChange` which requires 3 parameters ~ `onChange={(e) => {handleChange(e)}}`. See the problem? – Phil Apr 21 '21 at 05:17
  • Your `handleChange` handler expects 3 arguments but you pass only the first. `countMonth` and `countYear` aren't in scope as fas as I can tell. – Drew Reese Apr 21 '21 at 05:19
  • Yeah i tried adding those two as arguments but still doesn't work – Shuib Abdillahi Apr 21 '21 at 06:35

1 Answers1

-1

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)
  
  }
}
Pavan
  • 819
  • 6
  • 18