1
votes

Below is my parent component which handles the state of the app.

 function App() {   
    const [teamData, setTeamData] = useState<any | undefined>(undefined);
    return(
      <> 
          <Teams teams={teams} onTeamClick={() => setTeamData(team)} />
          <Modal teamData={teamData} />
      </>
    )
}

Next is my component which passes the state back up the tree. However, I am getting the following typescript error:

Cannot invoke an object which is possibly 'undefined'.

type Props = {
   teams: any[];
   onTeamClick: () => void;
}

function Teams({teams, onTeamClick}: Props) {
   return(
     <div>
       {teams.map(team => {
         // the error is coming from onTeamClick
         // No error if I change it to onTeamClick={onTeamClick}
         <Team name={team.name} onTeamClick={() => onTeamClick(team)} />
       })
     </div>
   )
}
2

2 Answers

2
votes

That's because here:

<Teams teams={teams} onTeamClick={() => setTeamData(team)} />

you are taking the team variable from nowhere, therefore it is undefined.

Doing this should be fine:

<Teams teams={teams} onTeamClick={ team => setTeamData(team) } />

I am not super familiar with React Hooks, but I think you might be able to do this, which is a bit shorter:

<Teams teams={teams} onTeamClick={ setTeamData } />
1
votes

It is undefined because the initial state from the hooks leads the compiler to believe it could possibly be undefined.

How about trying this ?

<Team name={team.name} onTeamClick={() => onTeamClick && onTeamClick(team)} />