Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

345
Visualizações
React runtime errors - What happens if an expected prop is not given? ErrorBoundary and PropTypes

I have a component Profile which might receive this a prop:

RootProfile.propTypes = {
  route: PropTypes.shape({
    params: PropTypes.shape({
      userData: PropTypes.oneOfType([
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
        PropTypes.shape({
          username: PropTypes.string.isRequired,
        }),
      ]),
    }),
  }).isRequired,
};

In the code of Profile, I do:

function RootProfile({route: { params }}){ 
   const currentUser = useCurrentUser();

   let { userData = currentUser.data } = params ?? {};

   // Consume the most up-to-date data from context
   userData = useUpdatedUserData(userData);

   if (userData.id) {
      return <Profile userData={userData} />
   }

   // We will need to fetch the user by username!
   return <ProfileFetcher username={userData.username} />
}

As you can see, if userData.id is not defined, I do not render the my lazy loading Profile component... Instead, I render my ProfileFetcher component, which just fetches the user data by username and stores it to my context (which I consume in RootProfile to re-render the screen when everything is ready).

My question is: what if, for an unexpected reason, Profile doesn't receive the "required" prop fields for its work? I mean, what if it doesn't receive neither userData.id nor userData.username?

Should I do something like

function RootProfile({route: { params }}){ 
   const currentUser = useCurrentUser();

   let { userData = currentUser.data } = params ?? {};

   // Consume the most up-to-date data from context
   userData = useUpdatedUserData(userData);

   if (userData.id) {
      return <Profile userData={userData} />
   } else if (userData.username) {
      // We will need to fetch the user by username!
      return <ProfileFetcher username={userData.username} />
   } else {
     throw new Error("id or username is required");
   }
}

?? I mean, is it considered "correct" to throw an error inside a React component?

Or, should all these situations be handled with ErrorBoundaries and PropTypes?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you think that the prop may be undefined consider removing isRequired and making it optional. However, in answer to your question PropTypes library doesn't throw errors in production mode so you can't catch it with an ErrorBoundary you have to check it menually.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda