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 15 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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.

11 changes: 9 additions & 2 deletions src/pages/FacilityOrganization/FacilityOrganizationView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,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,6 +28,10 @@ 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 { data: children, isLoading } = useQuery({
queryKey: [
Expand All @@ -35,15 +41,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 @@ -61,6 +67,7 @@ export default function FacilityOrganizationView({ id, facilityId }: Props) {
onChange={(e) => {
setSearchQuery(e.target.value);
setPage(1); // Reset to first page on search
setDebouncedParams(e.target.value);
}}
className="w-full"
/>
Expand Down
20 changes: 12 additions & 8 deletions src/pages/Organization/OrganizationFacilities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,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 +31,17 @@ export default function OrganizationFacilities({
const { qParams, Pagination, advancedFilter, resultsPerPage, updateQuery } =
useFilters({ limit: 14, cacheBlacklist: ["facility"] });

const [debouncedParams, setDebouncedParams] = useDebouncedState(qParams, 500);

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 +51,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 @@ -62,12 +65,13 @@ export default function OrganizationFacilities({
type="text"
placeholder="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
13 changes: 11 additions & 2 deletions src/pages/Organization/OrganizationView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,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 +27,22 @@ 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 [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 { 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 @@ -56,6 +64,7 @@ export default function OrganizationView({ id, navOrganizationId }: Props) {
onChange={(e) => {
setSearchQuery(e.target.value);
setPage(1); // Reset to first page on search
setDebouncedParams(e.target.value);
}}
className="w-full"
/>
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