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?
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.