1

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 Answers 2

2

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 } />
Sign up to request clarification or add additional context in comments.

2 Comments

Trying the first one, but still seem to get the same error. With the second one how will I pass the team in with this ?
the second example is written in point-free syntax medium.freecodecamp.org/…
1

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)} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.