mardi 9 juin 2020

Should a React component prop be required when the data is fetched from the backend API?

Like any other app, for rendering a specific section of my React app, I'm expecting to receive a list of items from my backend API. I've created a typical Card component to display the data of each item. This Card component has a parent component which is common for all of the items. It would be something like this:

<ParentComponent>
 <CardItem headline image/>
</ParentComponent>

The props headlineand image are required, so in theory, I should always receive them from my API. Therefore, I've set these props as required in my component:

CardItem.propTypes = {
  headline: PropTypes.string.isRequired,
  image: PropTypes.string.isRequired,
}

As we all know, as our app grows, it can always happen that for some specific reason, even though these props are required, I could receive an undefined value. For this reason, I like doing my components bulletproof and, even though those props are required, I always do a conditional rendering for avoiding the app to break:

{headline && (
  <Component/>
)}

For other components I just check at the very top if the prop exists, otherwise, I return null:

if (!itemId) return null

While unit testing my components, I make sure this behavior is tested so that if I receive any undefined vale from my API, the app doesn't break. I've realized that Jest keeps warning me because of this:

Warning: Failed prop type: The prop headline is marked as required in CardItem, but its value is undefined.

It makes me wonder if my approach is not the right one so here my doubts:

  1. Is my approach correct and there is a way to avoid these warnings on Jest?
  2. Should the props of a component never be required when the data is received from an API?
  3. Instead of checking in the component children, the parent component should not render the children if the props don't exist? - This one feels like it is not the correct one at all but I'm adding it just in case it is a valid approach.

Please don't let your response be influenced by the fact that I'm checking props like headline or image, I know for something like this I can always render conditionally. Think more of the case of an itemId or similar which are props 100% required for the correct rendering/behavior.

Aucun commentaire:

Enregistrer un commentaire