Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
72 changes: 72 additions & 0 deletions apps/customer/src/app/(tabs)/main/_apis/searchAddressByKakao.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"use client";

import type { AddressSearchItem } from "../_types/address-search";

export function searchAddressByKakao(
keyword: string,
size = 10
): Promise<AddressSearchItem[]> {
return new Promise((resolve, reject) => {
const trimmedKeyword = keyword.trim();

if (!trimmedKeyword) {
resolve([]);
return;
}

if (
typeof window === "undefined" ||
!window.kakao ||
!window.kakao.maps ||
!window.kakao.maps.services
) {
reject(new Error("Kakao services library is not loaded."));
return;
}

const geocoder = new window.kakao.maps.services.Geocoder();

geocoder.addressSearch(
trimmedKeyword,
(result: KakaoAddressSearchResult[], status: string) => {
const { kakao } = window;

if (status === kakao.maps.services.Status.ZERO_RESULT) {
resolve([]);
return;
}

if (status !== kakao.maps.services.Status.OK) {
reject(new Error("주소 검색 중 오류가 발생했습니다."));
return;
}

const mapped = result.slice(0, size).map(
(item: KakaoAddressSearchResult, index: number) => {
const lotNumberAddress =
item.address?.address_name || item.address_name || "";

const roadAddress =
item.road_address?.address_name || item.address_name || "";

return {
id: `${item.x}-${item.y}-${index}`,
label: roadAddress || lotNumberAddress,
lotNumberAddress,
roadAddress,
longitude: Number(item.x),
latitude: Number(item.y),
};
}
);

resolve(mapped);
},
{
page: 1,
size,
analyze_type: window.kakao.maps.services.AnalyzeType.SIMILAR,
}
);
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"use client";

import { useEffect, useRef, useState } from "react";
import { BottomSheet, Input, Icon } from "@compasser/design-system";
import type { AddressSearchItem } from "../_types/address-search";
import { searchAddressByKakao } from "../_apis/searchAddressByKakao";

interface AddressSearchBottomSheetProps {
open: boolean;
onClose: () => void;
onSelectAddress: (item: AddressSearchItem) => void;
}

export default function AddressSearchBottomSheet({
open,
onClose,
onSelectAddress,
}: AddressSearchBottomSheetProps) {
const [keyword, setKeyword] = useState("");
const [results, setResults] = useState<AddressSearchItem[]>([]);
const [isSearching, setIsSearching] = useState(false);

const debounceRef = useRef<number | null>(null);

useEffect(() => {
if (!open) {
setKeyword("");
setResults([]);
setIsSearching(false);
}
}, [open]);

useEffect(() => {
if (!open) {
return;
}

const trimmedKeyword = keyword.trim();

if (!trimmedKeyword) {
setResults([]);
setIsSearching(false);
return;
}

if (debounceRef.current) {
window.clearTimeout(debounceRef.current);
}

debounceRef.current = window.setTimeout(async () => {
try {
setIsSearching(true);
const searched = await searchAddressByKakao(trimmedKeyword, 10);
setResults(searched);
} catch (error) {
console.error(error);
setResults([]);
} finally {
setIsSearching(false);
}
Comment on lines +50 to +60
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "AddressSearchBottomSheet.tsx" | head -5

Repository: CUK-Compasser/FE

Length of output: 136


🏁 Script executed:

cat -n apps/customer/src/app/\(tabs\)/main/_components/AddressSearchBottomSheet.tsx | sed -n '1,100p'

Repository: CUK-Compasser/FE

Length of output: 3180


🏁 Script executed:

find . -type f -name "*searchAddressByKakao*" -o -path "*_apis*" -name "*search*" | head -10

Repository: CUK-Compasser/FE

Length of output: 125


🏁 Script executed:

cat -n apps/customer/src/app/\(tabs\)/main/_apis/searchAddressByKakao.ts 2>/dev/null | head -50

Repository: CUK-Compasser/FE

Length of output: 1772


🏁 Script executed:

rg "window\.setTimeout.*async" apps/customer/src --type ts --type tsx -A 3 | head -50

Repository: CUK-Compasser/FE

Length of output: 87


🏁 Script executed:

rg "setTimeout.*async" apps/ --type ts --type tsx -c | head -20

Repository: CUK-Compasser/FE

Length of output: 87


🏁 Script executed:

rg "setTimeout.*async" apps/ -A 3 2>/dev/null | head -60

Repository: CUK-Compasser/FE

Length of output: 532


🏁 Script executed:

rg "debounce|setIsSearching" apps/customer/src --max-count 20

Repository: CUK-Compasser/FE

Length of output: 1331


검색 응답 경쟁 상태(race condition) 방어가 필요합니다.

Line 50-60의 비동기 API 호출에서 이전 요청의 응답이 늦게 도착하면 최신 키워드 결과를 덮어쓸 수 있습니다. 사용자가 "A" 검색 후 "B"를 검색할 때 "A"의 응답이 "B"의 응답보다 나중에 도착하면 잘못된 결과가 표시됩니다. 또한 시트를 닫은 직후에도 이전 요청의 응답으로 상태가 갱신될 수 있습니다. 요청 식별자 또는 취소 플래그를 사용하여 최신 요청만 반영해 주세요.

제안 코드
   const debounceRef = useRef<number | null>(null);
+  const requestSeqRef = useRef(0);

   useEffect(() => {
+    let cancelled = false;
     if (!open) {
       return;
     }
@@
-    debounceRef.current = window.setTimeout(async () => {
+    const requestId = ++requestSeqRef.current;
+    debounceRef.current = window.setTimeout(async () => {
       try {
         setIsSearching(true);
         const searched = await searchAddressByKakao(trimmedKeyword, 10);
-        setResults(searched);
+        if (!cancelled && requestId === requestSeqRef.current) {
+          setResults(searched);
+        }
       } catch (error) {
-        console.error(error);
-        setResults([]);
+        if (!cancelled && requestId === requestSeqRef.current) {
+          console.error(error);
+          setResults([]);
+        }
       } finally {
-        setIsSearching(false);
+        if (!cancelled && requestId === requestSeqRef.current) {
+          setIsSearching(false);
+        }
       }
     }, 250);

     return () => {
+      cancelled = true;
       if (debounceRef.current) {
         window.clearTimeout(debounceRef.current);
       }
     };
   }, [keyword, open]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/customer/src/app/`(tabs)/main/_components/AddressSearchBottomSheet.tsx
around lines 50 - 60, The async search block can be overwritten by out-of-order
responses; add a request identifier or cancellation flag to ensure only the
latest request updates state: create a ref like latestRequestIdRef and increment
it before calling searchAddressByKakao (or create an AbortController if
searchAddressByKakao supports aborting) then capture the current id in the async
callback and, before calling setResults/setIsSearching, verify the id matches
latestRequestIdRef and that the sheet is still open (use an isOpen or isMounted
ref); also ensure any previous pending request is aborted or ignored when the
sheet closes. Use the existing debounceRef and
trimmedKeyword/searchAddressByKakao/setResults/setIsSearching identifiers to
locate where to add this logic.

}, 250);

return () => {
if (debounceRef.current) {
window.clearTimeout(debounceRef.current);
}
};
}, [keyword, open]);

const handleQuickSelect = () => {
onSelectAddress({
id: "catholic-univ",
label: "가톨릭대 주변 탐색",
lotNumberAddress: "경기도 부천시 원미구 역곡동 일대",
roadAddress: "가톨릭대학교 성심교정 주변",
longitude: 126.8016,
latitude: 37.4875,
});
};

const handleSelectItem = (item: AddressSearchItem) => {
onSelectAddress(item);
};

return (
<BottomSheet
open={open}
onClose={onClose}
variant="default"
overlay
closeOnOverlayClick
showHandle
className="w-full"
contentClassName="px-[1.6rem] pt-[0.8rem] pb-[2rem]"
>
<Input
inputStyle="address"
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
placeholder="위치 입력"
/>

<button
type="button"
onClick={handleQuickSelect}
className="ml-[0.6rem] mt-[1rem] inline-flex items-center rounded-[999px] border border-secondary-variant px-[0.8rem] py-[0.2rem]"
>
<Icon
name="Pin"
width={20}
height={20}
className="mr-[0.4rem]"
/>
<span className="body2-r text-default">가톨릭대 주변 탐색</span>
</button>

{results.length > 0 && (
<div className="mt-[1.2rem] max-h-[32rem] overflow-y-auto">
{results.map((item) => (
<button
key={item.id}
type="button"
onClick={() => handleSelectItem(item)}
className="block w-full border-b border-gray-100 px-[0.6rem] pt-[0.6rem] pb-[0.8rem] text-left"
>
<p className="body2-r text-default">{item.lotNumberAddress}</p>
<p className="caption1-r text-gray-500">{item.roadAddress}</p>
</button>
))}
</div>
)}

{keyword.trim() && isSearching && (
<p className="mt-[1.2rem] px-[0.6rem] text-center caption1-r text-gray-500">
검색 중...
</p>
)}

{keyword.trim() && !isSearching && results.length === 0 && (
<p className="mt-[1.2rem] px-[0.6rem] text-center caption1-r text-gray-500">
검색 결과가 없습니다.
</p>
)}
</BottomSheet>
);
}
Loading
Loading