-
Notifications
You must be signed in to change notification settings - Fork 518
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Prefill Structured Data; Add Edit Links for Structured #9992
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughThis pull request introduces a comprehensive set of changes across multiple components and files, focusing on enhancing localization, improving type safety, and refactoring components related to patient information such as allergies, medications, diagnoses, and symptoms. The changes include adding new localization entries, removing an endpoint, updating component structures, introducing new layout components, and improving type definitions for allergy verification and clinical statuses. Changes
Suggested labels
Suggested reviewers
Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (4)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ Context from checks skipped due to timeout of 90000ms (1)
🔇 Additional comments (5)
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
Deploying care-fe with Cloudflare Pages
|
CARE Run #4346
Run Properties:
|
Project |
CARE
|
Branch Review |
structured_prefills
|
Run status |
Passed #4346
|
Run duration | 02m 06s |
Commit |
82c70b5bc6: Prefill Structured Data; Add Edit Links for Structured
|
Committer | Gigin George |
View all properties for this run ↗︎ |
Test results | |
---|---|
Failures |
0
|
Flaky |
0
|
Pending |
0
|
Skipped |
0
|
Passing |
5
|
View all changes introduced in this branch ↗︎ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
src/components/Medicine/MedicationRequestTable/index.tsx (1)
Line range hint
211-218
: Ensure consistent usage of status valuesThere's an inconsistency in the status value for "on hold": in the filtering logic, you use
"on_hold"
, but in thegetStatusVariant
function, you check for"on-hold"
(with a hyphen). This could lead to incorrect badge variants being displayed.Apply this diff to correct the status value in
getStatusVariant
:switch (status) { case "active": return "default"; - case "on-hold": + case "on_hold": return "secondary"; case "cancelled": return "destructive"; case "completed": return "primary"; default: return "secondary"; }
🧹 Nitpick comments (8)
src/components/Medicine/MedicationRequestTable/index.tsx (3)
56-63
: UsepatientId
inpathParams
for consistencyIn the
useQuery
call, consider using the already definedpatientId
variable instead ofencounter?.patient?.id || ""
in thepathParams
. This improves readability and ensures consistency throughout the code.Apply this diff:
- pathParams: { patientId: encounter?.patient?.id || "" }, + pathParams: { patientId: patientId || "" },
56-63
: Add error handling for data fetchingConsider adding error handling to manage potential errors during data fetching with
useQuery
. This ensures the component can gracefully handle and display error states to the user.
Line range hint
280-286
: Implement the TODO for displaying dose and rateThere's a TODO comment indicating that the Medicine Administration Sheet needs to be rebuilt to properly display the dose and rate information. Implementing this functionality will enhance the completeness of the prescription entries.
Do you want me to help implement the dose and rate display or open a GitHub issue to track this task?
src/types/emr/allergyIntolerance/allergyIntolerance.ts (1)
41-47
: Consider using i18n for verification status labels.The hardcoded English strings in
ALLERGY_VERIFICATION_STATUS
should be moved to i18n files for better internationalization support.-export const ALLERGY_VERIFICATION_STATUS = { - unconfirmed: "Unconfirmed", - confirmed: "Confirmed", - refuted: "Refuted", - presumed: "Presumed", - "entered-in-error": "Entered in Error", -}; +export const ALLERGY_VERIFICATION_STATUS = { + unconfirmed: t("allergy.verification.unconfirmed"), + confirmed: t("allergy.verification.confirmed"), + refuted: t("allergy.verification.refuted"), + presumed: t("allergy.verification.presumed"), + "entered-in-error": t("allergy.verification.entered_in_error"), +};src/components/Patient/symptoms/list.tsx (1)
69-97
: Consider extracting common layout pattern.The layout component pattern is repeated across different list components. Consider creating a shared ListLayout component.
// src/components/shared/ListLayout.tsx interface ListLayoutProps { title: string; editHref?: string; facilityId?: string; children: ReactNode; } export const ListLayout = ({ title, editHref, facilityId, children, }: ListLayoutProps) => { return ( <Card> <CardHeader className="px-4 py-0 pt-4 flex justify-between flex-row"> <CardTitle>{t(title)}</CardTitle> {facilityId && editHref && ( <Link href={editHref} className="flex items-center gap-1 text-sm hover:text-gray-500" > <PencilIcon size={12} /> {t("edit")} </Link> )} </CardHeader> <CardContent>{children}</CardContent> </Card> ); };src/components/Patient/allergy/list.tsx (1)
114-119
: Consider using a more explicit sorting function.The sorting logic could be more readable with a dedicated function and explicit return values.
- .sort((a, _b) => { - if (a.clinical_status === "inactive") { - return 1; - } - return -1; - }) + .sort((a, b) => { + const isAInactive = a.clinical_status === "inactive"; + const isBInactive = b.clinical_status === "inactive"; + return isAInactive === isBInactive ? 0 : isAInactive ? 1 : -1; + })src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (1)
510-529
: Enhance type safety with runtime validation.The desktop view implementation could benefit from additional type safety.
Consider this safer implementation:
onValueChange={(value) => { - if (value in ALLERGY_VERIFICATION_STATUS) { + if (Object.keys(ALLERGY_VERIFICATION_STATUS).includes(value)) { onUpdate?.({ verification_status: value as AllergyVerificationStatus, }); } }}src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)
77-101
: Consider adding error handling for the query.The data fetching implementation looks good but could benefit from error handling.
Consider adding error handling:
-const { data: patientMedications } = useQuery({ +const { data: patientMedications, error } = useQuery({ queryKey: ["medications", patientId], queryFn: query(medicationRequestApi.list, { pathParams: { patientId }, }), }); useEffect(() => { + if (error) { + toast.error("Failed to fetch medications"); + return; + } if (patientMedications?.results && !medications.length) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
public/locale/en.json
(1 hunks)src/Utils/request/api.tsx
(0 hunks)src/components/Medicine/MedicationRequestTable/index.tsx
(5 hunks)src/components/Patient/allergy/list.tsx
(5 hunks)src/components/Patient/diagnosis/list.tsx
(3 hunks)src/components/Patient/symptoms/list.tsx
(3 hunks)src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx
(4 hunks)src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx
(4 hunks)src/components/Questionnaire/QuestionnaireForm.tsx
(1 hunks)src/components/Questionnaire/data/StructuredFormData.tsx
(1 hunks)src/pages/Encounters/PrintPrescription.tsx
(2 hunks)src/pages/Encounters/tabs/EncounterMedicinesTab.tsx
(1 hunks)src/pages/Encounters/tabs/EncounterUpdatesTab.tsx
(2 hunks)src/types/emr/allergyIntolerance/allergyIntolerance.ts
(2 hunks)src/types/emr/medicationRequest/medicationRequestApi.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- src/Utils/request/api.tsx
🧰 Additional context used
📓 Learnings (1)
src/components/Questionnaire/QuestionnaireForm.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9838
File: src/components/Questionnaire/QuestionnaireForm.tsx:100-105
Timestamp: 2025-01-14T05:04:43.093Z
Learning: The QuestionnaireForm component in care_fe uses raviger's useNavigationPrompt hook for handling navigation prompts, replacing a previous custom hook implementation.
🔇 Additional comments (26)
src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1)
1-8
: Component replacement is correctly implementedThe
MedicationRequestTable
component replacesMedicineAdministrationSheet
appropriately. The component is correctly imported and rendered with the requiredfacilityId
prop.src/types/emr/medicationRequest/medicationRequestApi.ts (1)
6-13
: API module is correctly definedThe
medicationRequestApi
module is properly structured, and the endpoint for listing medication requests is correctly specified with the appropriate path, method, and response type.src/types/emr/allergyIntolerance/allergyIntolerance.ts (2)
4-11
: LGTM! Well-defined type definitions enhance type safety.The introduction of
AllergyVerificationStatus
andAllergyClinicalStatus
types helps prevent invalid values and improves code maintainability.
16-17
: LGTM! Type-safe interface updates.Replacing string types with specific enum-like types improves type safety and provides better IntelliSense support.
Also applies to: 31-32
src/pages/Encounters/tabs/EncounterUpdatesTab.tsx (2)
10-13
: LGTM! Consistent prop addition.The facilityId prop is correctly added to the component's props.
22-44
: LGTM! Consistent prop passing to child components.The facilityId prop is consistently passed to all relevant list components.
src/components/Patient/symptoms/list.tsx (2)
18-18
: LGTM! Clean props interface update.The facilityId prop is correctly added as optional.
Also applies to: 21-25
36-65
: LGTM! Well-structured component refactoring.The use of SymptomListLayout improves code organization and reusability.
src/components/Patient/diagnosis/list.tsx (2)
69-97
: Apply the same layout component suggestion.Similar to the symptoms list, consider using a shared ListLayout component here as well.
84-92
: Verify the requirement for encounterId check.The edit link visibility differs from the symptoms component. Verify if both components should have the same conditions.
src/components/Questionnaire/data/StructuredFormData.tsx (5)
43-61
: LGTM! Well-structured allergy questionnaire definition.The allergy intolerance questionnaire follows the established pattern and includes all required fields.
63-81
: LGTM! Well-structured medication questionnaire definition.The medication statement questionnaire maintains consistency with other questionnaire definitions.
83-101
: LGTM! Well-structured diagnosis questionnaire definition.The diagnosis questionnaire follows the same pattern as other questionnaires.
103-121
: LGTM! Well-structured symptom questionnaire definition.The symptom questionnaire maintains consistency with other questionnaire definitions.
126-129
: LGTM! Questionnaires properly exported.All new questionnaires are correctly added to the FIXED_QUESTIONNAIRES export.
src/components/Patient/allergy/list.tsx (3)
26-26
: LGTM! Optional facilityId prop added.The facilityId prop is correctly marked as optional.
31-35
: LGTM! Component signature updated.The AllergyList component signature properly includes the new facilityId prop.
166-194
: LGTM! Well-structured layout component.The AllergyListLayout component properly handles the conditional rendering of the edit link based on facilityId and encounterId.
src/pages/Encounters/PrintPrescription.tsx (1)
27-27
: LGTM! API import and usage updated.The medicationRequestApi import and its usage in the query function are correctly implemented.
Also applies to: 96-96
src/components/Questionnaire/QuestionnaireForm.tsx (1)
101-101
: LGTM! Navigation prompt disabled in dev mode.Good improvement for developer experience. The change aligns with the retrieved learning about using raviger's useNavigationPrompt hook.
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (2)
50-53
: LGTM! Good type safety improvements.The imports are well-organized and improve type safety by introducing dedicated types and constants for allergy verification statuses.
Line range hint
355-371
: LGTM! Clean implementation of verification status handling.The mobile view implementation correctly uses type assertion and maps through the verification statuses dynamically.
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)
2-2
: LGTM! Well-organized imports.The imports are properly organized and include necessary dependencies for data fetching and notifications.
Also applies to: 4-5
46-46
: LGTM! Good separation of concerns.The API and utility imports maintain a clean separation of concerns.
Also applies to: 57-57
62-62
: LGTM! Clear interface definition.The props interface is well-defined with the new patientId requirement.
Also applies to: 72-72
public/locale/en.json (1)
1346-1346
: LGTM! Clear and consistent message.The new localization entry follows the established pattern and provides a clear message.
👋 Hi, @gigincg, This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (3)
src/pages/Encounters/EncounterShow.tsx (2)
Line range hint
91-156
: Clean up commented code and improve error handling.There's a significant amount of commented-out code that should be removed if no longer needed. Additionally, error handling could be improved.
Consider:
- Removing commented code if it's no longer needed
- Adding error boundaries for better error isolation
- Implementing comprehensive error states
- // const encounterQuery = useTanStackQueryInstead(routes.encounter.get, { - // pathParams: { id: consultationId }, - // }); - - // const consultationData = encounterQuery.data; - // const bedId = consultationData?.current_bed?.bed_object?.id;
Line range hint
179-285
: Enhance accessibility in navigation and tab components.The navigation and tab components need accessibility improvements:
- Add proper ARIA attributes for tab navigation
- Ensure keyboard navigation works correctly
- Add screen reader support
Example improvements:
<nav className="flex space-x-6 overflow-x-auto pb-2 pl-2" id="encounter_tab_nav" + role="tablist" + aria-label={t('encounter_tabs')} > {keysOf(tabs).map((tab) => ( <Link key={tab} className={tabButtonClasses(props.tab === tab)} href={`/facility/${facilityId}/encounter/${encounterData.id}/${tab}`} + role="tab" + aria-selected={props.tab === tab} + aria-controls={`${tab}-panel`} > {t(`ENCOUNTER_TAB__${tab}`)} </Link> ))} </nav>src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)
Line range hint
105-122
: Remove type casting and improve type safety in handleAddMedication.The FIXME comment indicates a type casting issue that should be addressed.
- value: newMedications as MedicationStatement[], // FIXME: Remove this cast + value: newMedications,Consider updating the MEDICATION_STATEMENT_INITIAL_VALUE type to ensure type safety without casting:
const MEDICATION_STATEMENT_INITIAL_VALUE: Omit<MedicationStatement, 'medication' | 'patient' | 'encounter' | 'id'> & { status: MedicationStatementStatus; } = { status: "active", reason: undefined, dosage_text: "", effective_period: undefined, information_source: MedicationStatementInformationSourceType.PATIENT, note: undefined, };
🧹 Nitpick comments (6)
src/pages/Encounters/EncounterShow.tsx (2)
Line range hint
22-34
: Consider splitting component responsibilities and improving data flow.The component handles multiple concerns (data fetching, routing, UI). Consider:
- Extracting tab configuration into a separate module
- Creating a custom hook for encounter data fetching
- Re-evaluating the removal of
EncounterProvider
as prop drilling might impact maintainabilityAlso applies to: 39-43
Line range hint
39-43
: Improve type safety and centralize route handling.Consider:
- Creating typed route constants
- Centralizing URL construction
- Adding route parameter validation
Example implementation:
// routes.ts export const encounterRoutes = { tab: (params: { facilityId: string, encounterId: string, tab: keyof typeof defaultTabs }) => `/facility/${params.facilityId}/encounter/${params.encounterId}/${params.tab}`, // ... other routes } as const;Also applies to: 246-259
src/components/Medicine/MedicationRequestTable/index.tsx (1)
Line range hint
82-90
: Enhance internationalization coverage.Several UI strings should be moved to i18n files to align with the PR objectives:
- "No matches found"
- "No Prescriptions"
- "No medications match"
- "No medications have been prescribed yet"
Consider moving these strings to the i18n files:
- <h3 className="font-medium"> - {searching ? "No matches found" : "No Prescriptions"} - </h3> - <p className="text-sm text-muted-foreground"> - {searching - ? `No medications match "${searchQuery}"` - : "No medications have been prescribed yet"} - </p> + <h3 className="font-medium"> + {searching ? t("no_matches_found") : t("no_prescriptions")} + </h3> + <p className="text-sm text-muted-foreground"> + {searching + ? t("no_medications_match", { query: searchQuery }) + : t("no_medications_prescribed")} + </p>Also applies to: 156-159
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)
85-102
: Consider adding loading state handling and race condition prevention.While the initialization logic works, there are a few improvements to consider:
- Add loading state handling to prevent UI flicker
- Add error handling for failed requests
- Prevent overwriting existing medications if they were manually added while fetching
useEffect(() => { - if (patientMedications?.results && !medications.length) { + if (patientMedications?.results && !medications.length && !isError) { updateQuestionnaireResponseCB({ ...questionnaireResponse, values: [ { type: "medication_statement", value: patientMedications.results, }, ], }); if (patientMedications.count > patientMedications.results.length) { toast.info( `Showing first ${patientMedications.results.length} of ${patientMedications.count} medication statements`, ); } + } else if (isError) { + toast.error("Failed to fetch existing medications"); } -}, [patientMedications]); +}, [patientMedications, isError]);src/types/emr/medicationStatement/medicationStatementApi.ts (2)
8-8
: Add type safety for path parameters.The path parameter
{patientId}
should be properly typed to ensure type safety when making API calls.Consider adding path parameter typing:
- path: "/api/v1/patient/{patientId}/medication/statement/", + path: "/api/v1/patient/{patientId}/medication/statement/" as const, + params: Type<{ patientId: string }>(),
6-12
: Consider adding CRUD operations for complete structured data support.Since this PR aims to add edit support for structured fields, consider extending the API to include:
- POST endpoint for creating new statements
- PUT/PATCH endpoint for updating statements
- DELETE endpoint for removing statements
This would provide a complete set of operations for managing medication statements.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
src/components/Facility/ConsultationDetails/EncounterContext.tsx
(0 hunks)src/components/Medicine/MedicationRequestTable/index.tsx
(5 hunks)src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx
(5 hunks)src/pages/Encounters/EncounterShow.tsx
(2 hunks)src/pages/Encounters/tabs/EncounterMedicinesTab.tsx
(1 hunks)src/types/emr/medicationStatement/medicationStatementApi.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- src/components/Facility/ConsultationDetails/EncounterContext.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (11)
src/pages/Encounters/tabs/EncounterMedicinesTab.tsx (1)
1-1
: LGTM! Clean component refactor.The switch to
MedicationRequestTable
with additional props improves type safety and data handling. Props are correctly derived from the parent component.Also applies to: 8-12
src/components/Medicine/MedicationRequestTable/index.tsx (3)
1-1
: LGTM! Well-implemented data fetching with React Query.The implementation follows best practices:
- Type-safe props interface
- Proper query key structure
- Query enabled condition prevents unnecessary requests
Also applies to: 17-17, 20-20, 22-26, 56-63
107-114
: LGTM! Edit functionality properly implemented.The edit button implementation:
- Follows UI/UX patterns
- Uses correct routing structure
- Maintains consistent styling
Line range hint
284-301
: Track technical debt: Rebuild Medicine Administration Sheet.There's a TODO comment and commented-out code for dose_and_rate handling. Let's ensure this is tracked for future implementation.
Would you like me to:
- Create a GitHub issue to track this technical debt?
- Help implement the dose_and_rate handling?
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (4)
Line range hint
1-48
: LGTM! Import statements and prop interface changes are well-organized.The new imports and the addition of the
patientId
prop align well with the enhanced functionality for medication management.
78-83
: LGTM! Data fetching implementation is correct.The query key and fetching logic are properly implemented using
@tanstack/react-query
.
124-143
: LGTM! Medication removal logic handles existing and new medications appropriately.The differentiation between existing and new medications is well implemented, preserving history for existing records while allowing complete removal of new ones.
238-264
: LGTM! The remove button implementation with tooltips enhances user experience.The UI changes effectively communicate the difference between removing new medications and marking existing ones as entered-in-error. The tooltips and icons provide clear visual feedback.
src/types/emr/medicationStatement/medicationStatementApi.ts (3)
1-4
: LGTM! Imports are well-structured.The imports are appropriate for the functionality, using proper type imports and consistent path aliasing.
14-14
: LGTM! Export is appropriate.The default export of the API constant follows the module pattern consistently.
6-12
: Verify the impact of switching from medicationRequest to medicationStatement.Based on the AI summary, this endpoint is replacing usage of
medicationRequestApi
. This architectural change might require:
- Data migration plan for existing medication requests
- Update of dependent components
- Backwards compatibility consideration
Let's verify the impact:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)
144-165
: Improve type safety and maintainability of status handling.The status handling could be improved by using type assertions and constants for better maintainability.
+const MEDICATION_STATUS = { + ENTERED_IN_ERROR: 'entered_in_error' as const +} as const; const medication = medications[medicationToDelete]; if (medication.id) { // For existing records, update status to entered-in-error const newMedications = medications.map((med, i) => i === medicationToDelete - ? { ...med, status: "entered_in_error" as const } + ? { ...med, status: MEDICATION_STATUS.ENTERED_IN_ERROR } : med, );
519-526
: Improve semantics of error state styling.The opacity styling for error state could be more semantic and maintainable.
- className={cn( - "grid grid-cols-1 lg:grid-cols-[280px,180px,170px,160px,300px,230px,180px,250px,180px,160px,48px] border-b hover:bg-gray-50/50", - { - "opacity-50": medication.status === "entered_in_error", - }, - )} + className={cn( + "grid grid-cols-1 lg:grid-cols-[280px,180px,170px,160px,300px,230px,180px,250px,180px,160px,48px] border-b hover:bg-gray-50/50", + "medication-row", + { + "medication-row--error": medication.status === MEDICATION_STATUS.ENTERED_IN_ERROR, + }, + )}Add the following CSS:
.medication-row--error { opacity: 0.5; pointer-events: none; }
319-344
: Extract tooltip text to constants.The tooltip text should be extracted to constants for better maintainability and reusability.
+const TOOLTIP_TEXT = { + ENTERED_IN_ERROR: t("medication_already_marked_as_error"), + REMOVE: t("remove_medication"), +} as const; <TooltipContent> - {medication.status === "entered_in_error" - ? t("medication_already_marked_as_error") - : t("remove_medication")} + {medication.status === MEDICATION_STATUS.ENTERED_IN_ERROR + ? TOOLTIP_TEXT.ENTERED_IN_ERROR + : TOOLTIP_TEXT.REMOVE} </TooltipContent>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx
(7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: cypress-run (1)
- GitHub Check: OSSAR-Scan
const { data: patientMedications } = useQuery({ | ||
queryKey: ["medications", patientId], | ||
queryFn: query(medicationRequestApi.list, { | ||
pathParams: { patientId }, | ||
}), | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error and loading state handling for the query.
The useQuery implementation lacks error handling and loading state management, which could lead to poor user experience when the API call fails or is in progress.
const { data: patientMedications } = useQuery({
+ enabled: !!patientId,
queryKey: ["medications", patientId],
queryFn: query(medicationRequestApi.list, {
pathParams: { patientId },
}),
});
+const isLoading = !patientMedications;
+if (isLoading) {
+ return <LoadingSpinner />;
+}
Committable suggestion skipped: line range outside the PR's diff.
useEffect(() => { | ||
if (patientMedications?.results && !medications.length) { | ||
updateQuestionnaireResponseCB({ | ||
...questionnaireResponse, | ||
values: [ | ||
{ | ||
type: "medication_request", | ||
value: patientMedications.results, | ||
}, | ||
], | ||
}); | ||
if (patientMedications.count > patientMedications.results.length) { | ||
toast.info( | ||
`Showing first ${patientMedications.results.length} of ${patientMedications.count} medications`, | ||
); | ||
} | ||
} | ||
}, [patientMedications]); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix useEffect dependencies and potential race condition.
The useEffect hook is missing questionnaireResponse and updateQuestionnaireResponseCB in its dependency array, which could lead to stale closures. Also, there's a potential race condition if the medications are updated elsewhere while fetching.
useEffect(() => {
- if (patientMedications?.results && !medications.length) {
+ if (patientMedications?.results && !medications.length && !isLoading) {
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [
{
type: "medication_request",
value: patientMedications.results,
},
],
});
if (patientMedications.count > patientMedications.results.length) {
toast.info(
`Showing first ${patientMedications.results.length} of ${patientMedications.count} medications`,
);
}
}
-}, [patientMedications]);
+}, [patientMedications, medications.length, questionnaireResponse, updateQuestionnaireResponseCB]);
Committable suggestion skipped: line range outside the PR's diff.
…structured_prefills
Proposed Changes
@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
Release Notes
New Features
Improvements
Refactoring