I am pretty new to typescript and am not sure how to best go about this rather common scenario. I fetch data and pass it into a template component as such:
const ProfilePage: FC = (): JSX.Element => {
const { data, isDataLoading } = useProfileData();
return (
<ProfileTemplate
data={!isDataLoading && data}
/>
);
};
This is the ProfileTemplate component
import { profile_data, Maybe } from '../api-client';
type ProfileProps = {
data: Maybe<profile_data>;
}
export const ProfileTemplate: FC<ProfileProps> = ({ data }): JSX.Element => {
...
<StaticField label="First Name" text={data.first_name} />
<StaticField label="Last Name" text={data.last_name} />
...
}
Calling it as such results in Type 'false | Maybe<profile>' is not assignable to type 'Maybe<profile>'. I can remove the conditional which checks isDataLoading first, however I then get object is possibly null errors in my <StaticField> components.
first_name and last_name can be null or empty in the database. Although I realize that's not what's causing the object is possibly null errors, rather an empty profile_data object, when no data has been returned from the server yet.
How should I best handle this situation?
My `<StaticField>` component looks like so: interface Props {
label: string;
text?: Maybe<string>;
}
export const StaticField: FunctionComponent<Props> = ({ label, text }): JSX.Element => {
return (
<Box>
<Text color="gray.BlackCoral" className={classes.label}>
{label}
</Text>
<Text>{text}</Text>
</Box>
);
};
useProfileData?