Skip to content
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

Added debouncing for APIs #9801

Closed
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
ce241c3
Merge pull request #1 from ohcnetwork/develop
i0am0arunava Nov 6, 2024
80e48d6
Merge pull request #2 from ohcnetwork/develop
i0am0arunava Nov 6, 2024
3f5fcd3
Merge pull request #3 from ohcnetwork/develop
i0am0arunava Nov 6, 2024
4cc9892
Merge pull request #4 from ohcnetwork/develop
i0am0arunava Nov 6, 2024
9a2ac6f
Merge pull request #5 from ohcnetwork/develop
i0am0arunava Jan 2, 2025
2323a97
Merge pull request #6 from ohcnetwork/develop
i0am0arunava Jan 6, 2025
6f9e820
added debopuncing for that 3 apis
i0am0arunava Jan 6, 2025
97d3e71
added debopuncing for that 3 apis
i0am0arunava Jan 6, 2025
50fa549
added debopuncing for that 3 apis
i0am0arunava Jan 6, 2025
dd876e0
Merge branch 'develop' into issue/9660/addDebouncingForAPI
i0am0arunava Jan 6, 2025
7934651
added debopuncing for that 3 apis
i0am0arunava Jan 6, 2025
64ecadf
added useDebounceState hook instead of useDebounce
i0am0arunava Jan 6, 2025
0ff0e86
Merge remote-tracking branch 'fh/develop' into issue/9660/addDebounci…
i0am0arunava Jan 6, 2025
26a4850
Merge branch 'issue/9660/addDebouncingForAPI' of https://github.com/i…
i0am0arunava Jan 6, 2025
9615a9b
usedebouncestate updated work
i0am0arunava Jan 7, 2025
1afa00d
en.json updated, debouncing is added all the requested changes are done
i0am0arunava Jan 9, 2025
a22eaa7
en.json updated, debouncing is added all the requested changes are done
i0am0arunava Jan 9, 2025
4bf3f64
Merge branch 'develop' into issue/9660/addDebouncingForAPI
i0am0arunava Jan 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion public/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@
"LOG_UPDATE_FIELD_LABEL__ventilator_spo2": "SpO₂",
"LOG_UPDATE_UPDATED_NOTIFICATION": "{{ roundType }} updated successfully",
"NORMAL": "Brief Update",
"no_sub_organizations_found": "No sub_organizations found",
"no_organizations_found_matching": "No organizations found matching",
"NURSING_CARE_PROCEDURE__ascitic_tapping": "Ascitic Tapping",
"NURSING_CARE_PROCEDURE__bed_bath": "Bed Bath",
"NURSING_CARE_PROCEDURE__catheter_care": "Catheter Care",
Expand Down Expand Up @@ -1609,6 +1611,8 @@
"search": "Search",
"search_by_emergency_contact_phone_number": "Search by Emergency Contact Phone Number",
"search_by_emergency_phone_number": "Search by Emergency Phone Number",
"search_facilities": "Search Facilities",
"search_by_name": "Search by name",
"search_by_patient_name": "Search by Patient Name",
"search_by_patient_no": "Search by Patient Number",
"search_by_phone_number": "Search by Phone Number",
Expand Down Expand Up @@ -1700,6 +1704,7 @@
"spokes": "Spoke Facilities",
"srf_id": "SRF ID",
"staff_list": "Staff List",
"staff": "Staff",
"start_consultation": "Start Consultation",
"start_datetime": "Start Date/Time",
"start_dosage": "Start Dosage",
Expand Down Expand Up @@ -1930,4 +1935,4 @@
"you_need_at_least_a_location_to_create_an_assest": "You need at least a location to create an assest.",
"zoom_in": "Zoom In",
"zoom_out": "Zoom Out"
}
}
22 changes: 15 additions & 7 deletions src/pages/FacilityOrganization/FacilityOrganizationView.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import { Link } from "raviger";
import { useState } from "react";
import { useTranslation } from "react-i18next";

import CareIcon from "@/CAREUI/icons/CareIcon";

Expand All @@ -11,6 +12,8 @@ import { Input } from "@/components/ui/input";

import Pagination from "@/components/Common/Pagination";

import useDebouncedState from "@/hooks/useDebouncedState";

import routes from "@/Utils/request/api";
import query from "@/Utils/request/query";

Expand All @@ -26,7 +29,11 @@ export default function FacilityOrganizationView({ id, facilityId }: Props) {
const [page, setPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");
const limit = 12; // 3x4 grid

const [debouncedParams, setDebouncedParams] = useDebouncedState(
searchQuery,
500,
);
const { t } = useTranslation();
const { data: children, isLoading } = useQuery({
queryKey: [
"facilityOrganization",
Expand All @@ -35,15 +42,15 @@ export default function FacilityOrganizationView({ id, facilityId }: Props) {
id,
page,
limit,
searchQuery,
debouncedParams,
],
queryFn: query(routes.facilityOrganization.list, {
pathParams: { facilityId, organizationId: id },
queryParams: {
parent: id,
offset: (page - 1) * limit,
limit,
name: searchQuery || undefined,
name: debouncedParams || undefined,
},
}),
});
Expand All @@ -52,15 +59,16 @@ export default function FacilityOrganizationView({ id, facilityId }: Props) {
<FacilityOrganizationLayout id={id} facilityId={facilityId}>
<div className="space-y-6">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<h2 className="text-lg font-semibold">Organizations</h2>
<h2 className="text-lg font-semibold">{t("organizations")}</h2>
<div className="flex items-center gap-4 w-full sm:w-auto">
<div className="w-full sm:w-72">
<Input
placeholder="Search by name..."
placeholder={t("search_by_name")}
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setPage(1); // Reset to first page on search
setDebouncedParams(e.target.value);
}}
className="w-full"
/>
Expand Down Expand Up @@ -131,8 +139,8 @@ export default function FacilityOrganizationView({ id, facilityId }: Props) {
<Card className="col-span-full">
<CardContent className="p-6 text-center text-gray-500">
{searchQuery
? `No organizations found matching "${searchQuery}"`
: "No sub-organizations found."}
? `${t("no_organizations_found_matching")} "${searchQuery}"`
: `${t("no_sub_organizations_found")}`}
</CardContent>
</Card>
)}
Expand Down
27 changes: 16 additions & 11 deletions src/pages/Organization/OrganizationFacilities.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
import { Link } from "raviger";
import { useTranslation } from "react-i18next";

import CareIcon from "@/CAREUI/icons/CareIcon";

Expand All @@ -9,6 +10,7 @@ import { Input } from "@/components/ui/input";

import { Avatar } from "@/components/Common/Avatar";

import useDebouncedState from "@/hooks/useDebouncedState";
import useFilters from "@/hooks/useFilters";

import routes from "@/Utils/request/api";
Expand All @@ -30,15 +32,17 @@ export default function OrganizationFacilities({
const { qParams, Pagination, advancedFilter, resultsPerPage, updateQuery } =
useFilters({ limit: 14, cacheBlacklist: ["facility"] });

const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);
const { t } = useTranslation();
const { data: facilities, isLoading } = useQuery({
queryKey: ["organizationFacilities", id, qParams],
queryKey: ["organizationFacilities", id, debouncedParams],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update query parameters to match the debouncing split.

If implementing the suggested split of debounced parameters, update the query parameters accordingly.

 queryKey: ["organizationFacilities", id, debouncedParams],
 queryFn: query(routes.facility.list, {
   queryParams: {
-    page: debouncedParams.page,
+    page: qParams.page,
     limit: resultsPerPage,
-    offset: (debouncedParams.page - 1) * resultsPerPage,
+    offset: (qParams.page - 1) * resultsPerPage,
     organization: id,
-    name: debouncedParams.name,
+    name: debouncedSearch || undefined,
     ...advancedFilter.filter,
   },
 }),

Also applies to: 45-49

queryFn: query(routes.facility.list, {
queryParams: {
page: qParams.page,
page: debouncedParams.page,
limit: resultsPerPage,
offset: (qParams.page - 1) * resultsPerPage,
offset: (debouncedParams.page - 1) * resultsPerPage,
organization: id,
name: qParams.name,
name: debouncedParams.name,
...advancedFilter.filter,
},
}),
Expand All @@ -48,7 +52,7 @@ export default function OrganizationFacilities({
if (!id) {
return null;
}

console.log("ddd", debouncedParams);
return (
<OrganizationLayout id={id} navOrganizationId={navOrganizationId}>
<div className="space-y-6">
Expand All @@ -60,14 +64,15 @@ export default function OrganizationFacilities({
<div className="flex gap-2">
<Input
type="text"
placeholder="Search facilities..."
placeholder={t("search_facilities")}
value={qParams.name || ""}
onChange={(e) =>
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
})
}
});
setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
}}
Comment on lines +69 to +75
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update onChange handler to match separated debouncing

The onChange handler should be updated to match the separated debouncing logic for search and pagination.

 onChange={(e) => {
   updateQuery({
     name: e.target.value,
     page: 1,
   });
-  setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
+  setDebouncedSearch(e.target.value);
 }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
})
}
});
setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
}}
onChange={(e) => {
updateQuery({
name: e.target.value,
page: 1,
});
setDebouncedSearch(e.target.value);
}}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update onChange handler to match separated debouncing

The onChange handler should be updated to match the separated debouncing logic for search and pagination.

 onChange={(e) => {
   updateQuery({
     name: e.target.value,
     page: 1,
   });
-  setDebouncedParams({ ...qParams, name: e.target.value, page: 1 });
+  setDebouncedSearch(e.target.value);
 }}

📝 Committable suggestion

no ,can not do this , this will return type error Argument of type 'string' is not assignable to parameter of type 'SetStateAction<QueryParam>'.ts(2345)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@i0am0arunava You're absolutely right. I apologize for the incorrect suggestion. Your current implementation using setDebouncedParams with the full query params object is the correct approach as it maintains proper TypeScript type safety. Please keep the existing implementation.

:thinking_face:
⟪ ⬚⬚⬚⬚⬚⬚⬚ ⟫
⟪ ⬚🐰⬚⬚⬚⬚⬚ ⟫
⟪ ⬚⬚⬚⬚⬚⬚⬚ ⟫


✏️ Learnings added
Learnt from: i0am0arunava
PR: ohcnetwork/care_fe#9801
File: src/pages/Organization/OrganizationFacilities.tsx:69-75
Timestamp: 2025-01-09T08:56:20.006Z
Learning: When using useDebouncedState with query parameters in TypeScript, ensure the debounced state maintains the same type as the original state (QueryParam). Avoid splitting into separate string states as it breaks type safety.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

className="max-w-sm"
/>
</div>
Expand Down Expand Up @@ -102,7 +107,7 @@ export default function OrganizationFacilities({
) : facilities?.results?.length === 0 ? (
<Card className="col-span-full">
<CardContent className="p-6 text-center text-gray-500">
No facilities found.
{t("no_facilities_found")}
</CardContent>
</Card>
) : (
Expand Down Expand Up @@ -145,7 +150,7 @@ export default function OrganizationFacilities({
href={`/facility/${facility.id}`}
className="text-sm text-primary hover:underline"
>
View Facility
{t("view_facility")}
<Button
variant="ghost"
size="icon"
Expand Down
21 changes: 15 additions & 6 deletions src/pages/Organization/OrganizationView.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import { Link } from "raviger";
import { useState } from "react";
import { useTranslation } from "react-i18next";

import CareIcon from "@/CAREUI/icons/CareIcon";

Expand All @@ -11,6 +12,8 @@ import { Input } from "@/components/ui/input";

import Pagination from "@/components/Common/Pagination";

import useDebouncedState from "@/hooks/useDebouncedState";

import query from "@/Utils/request/query";
import { Organization, getOrgLabel } from "@/types/organization/organization";
import organizationApi from "@/types/organization/organizationApi";
Expand All @@ -25,16 +28,21 @@ interface Props {
export default function OrganizationView({ id, navOrganizationId }: Props) {
const [page, setPage] = useState(1);
const [searchQuery, setSearchQuery] = useState("");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be debounced instead

Copy link
Contributor Author

@i0am0arunava i0am0arunava Jan 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be debounced instead

i tried this one but problem is If searchQuery is debounced directly, the input's value={searchQuery} value will lag because the state only updates after the debounce delay

const [searchQuery, setSearchQuery] = useDebouncedState("", 500);

const limit = 12; // 3x4 grid

const { data: children, isLoading } = useQuery({
  queryKey: ["organization", id, "children", page, limit, searchQuery],
  queryFn: query(organizationApi.list, {
    queryParams: {
      parent: id,
      offset: (page - 1) * limit,
      limit,
      name: searchQuery || undefined,
    },
  }),
});

return (
  <Input
    placeholder="Search by name..."
    value={searchQuery}
    onChange={(e) => {
      setSearchQuery(e.target.value);
      setPage(1); // Reset to first page on search
    }}
    className="w-full"
  />
);

To fix this, we need two states but for distinct purposes:

A searchQuery state to handle the immediate user input.
A debounced state (debouncedParams) for triggering the query.

const limit = 12; // 3x4 grid

const [debouncedParams, setDebouncedParams] = useDebouncedState(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this okay ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nope. i don't see any purpose for having two states for debouncing 1 variable

searchQuery,
500,
);
const limit = 12; // 3x4 grid
const { t } = useTranslation();
const { data: children, isLoading } = useQuery({
queryKey: ["organization", id, "children", page, limit, searchQuery],
queryKey: ["organization", id, "children", page, limit, debouncedParams],
queryFn: query(organizationApi.list, {
queryParams: {
parent: id,
offset: (page - 1) * limit,
limit,
name: searchQuery || undefined,
name: debouncedParams || undefined,
},
}),
});
Expand All @@ -51,11 +59,12 @@ export default function OrganizationView({ id, navOrganizationId }: Props) {
<h2 className="text-lg font-semibold">Organizations</h2>
<div className="w-72">
<Input
placeholder="Search by name..."
placeholder={t("search_by_name")}
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setPage(1); // Reset to first page on search
setDebouncedParams(e.target.value);
}}
className="w-full"
/>
Expand Down Expand Up @@ -128,8 +137,8 @@ export default function OrganizationView({ id, navOrganizationId }: Props) {
<Card className="col-span-full">
<CardContent className="p-6 text-center text-gray-500">
{searchQuery
? `No organizations found matching "${searchQuery}"`
: "No sub-organizations found."}
? `${t("no_organizations_found_matching")} "${searchQuery}"`
: `${t("no_sub_organizations_found")}`}
</CardContent>
</Card>
)}
Expand Down
1 change: 0 additions & 1 deletion src/types/notes/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@ export interface Message {
created_by: UserBase;
updated_by: UserBase;
}

Loading