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
19 changes: 19 additions & 0 deletions src/analytics/ga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare global {
}

let isInitialized = false;
let currentUserId: string | null = null;

export const initGA = () => {
// 중복 초기화 방지
Expand All @@ -20,6 +21,19 @@ export const initGA = () => {
isInitialized = true;
};

// User-ID 설정 함수
export const setUserId = (userId: string | null) => {
currentUserId = userId;

if (typeof window !== 'undefined' && window.dataLayer) {
if (userId) {
window.dataLayer.push({
user_id: userId,
});
}
}
};

export const trackPageView = (path: string) => {
if (!isInitialized) {
console.warn('GA4가 초기화되지 않았습니다. initGA()를 먼저 호출하세요.');
Expand All @@ -45,8 +59,13 @@ export const trackEvent = (
}

if (typeof window !== 'undefined' && window.dataLayer) {
// 개발 환경에서만 debug_mode 활성화
const isDevelopment = import.meta.env.DEV;

window.dataLayer.push({
event: eventName,
...(isDevelopment && { debug_mode: true }),
...(currentUserId && { user_id: currentUserId }),
...parameters,
});
}
Expand Down
43 changes: 23 additions & 20 deletions src/components/home/HeaderToCarouselSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,28 +44,31 @@ function HeaderToCarouselSection() {
// 검색 이벤트 태깅
trackSearchStore(searchTerm, uniqueStores.length);

if (
uniqueStores.length === 1 &&
uniqueStores[0].name.toLowerCase().replace(/\s/g, '') ===
searchTerm.toLowerCase().replace(/\s/g, '')
) {
console.log('상세페이지로 이동:', uniqueStores[0].id);
navigate(`/store/${uniqueStores[0].id}`);
} else {
const isAddress = /동$|구$|역$/.test(searchTerm);
if (isAddress) {
navigate('/store-map', { state: { searchTerm } });
// GTM이 이벤트를 처리할 시간을 주기 위해 약간의 지연
setTimeout(() => {
if (
uniqueStores.length === 1 &&
uniqueStores[0].name.toLowerCase().replace(/\s/g, '') ===
searchTerm.toLowerCase().replace(/\s/g, '')
) {
console.log('상세페이지로 이동:', uniqueStores[0].id);
navigate(`/store/${uniqueStores[0].id}`);
} else {
navigate('/store-map', {
state: {
searchTerm,
center: gpsLocation
? { lat: gpsLocation.latitude, lng: gpsLocation.longitude }
: null,
},
});
const isAddress = /동$|구$|역$/.test(searchTerm);
if (isAddress) {
navigate('/store-map', { state: { searchTerm } });
} else {
navigate('/store-map', {
state: {
searchTerm,
center: gpsLocation
? { lat: gpsLocation.latitude, lng: gpsLocation.longitude }
: null,
},
});
}
}
}
}, 100);
} catch (error) {
console.error('Search failed, navigating to map page as fallback', error);
const isAddress = /동$|구$|역$/.test(inputValue);
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useLogout.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { useDispatch } from 'react-redux';
import { clearUser } from '@/store/userSlice';
import { setUserId } from '@/analytics/ga';

export const useLogout = () => {
const dispatch = useDispatch();

const handleLogout = () => {
localStorage.removeItem('accessToken');
dispatch(clearUser());
setUserId(null); // GA4 User-ID 제거
// window.location.reload();
};

Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useWithdraw.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useDispatch } from 'react-redux';
import axiosInstance from '@/api/axiosInstance';
import { clearUser } from '@/store/userSlice';
import { setUserId } from '@/analytics/ga';

export default function useWithdraw() {
const dispatch = useDispatch();
Expand All @@ -9,6 +10,7 @@ export default function useWithdraw() {
try {
await axiosInstance.delete('/api/v1/user/me');
dispatch(clearUser());
setUserId(null); // GA4 User-ID 제거
localStorage.removeItem('accessToken');
} catch (error) {
console.error('회원 탈퇴 실패:', error);
Expand Down
2 changes: 2 additions & 0 deletions src/pages/auth/NicknamePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import TopBar from '@/components/common/TopBar';
import { checkNicknameDuplicate, registerNickname } from '@/api/user';
import { useDispatch } from 'react-redux';
import { setUser } from '@/store/userSlice'; // ✅ ❷ 닉네임 저장용 액션
import { setUserId } from '@/analytics/ga';

export default function NicknamePage() {
const navigate = useNavigate();
Expand Down Expand Up @@ -67,6 +68,7 @@ export default function NicknamePage() {
try {
const result = await registerNickname(nickname); // 서버에서 등록 후 유저 정보 반환
dispatch(setUser({ id: result.email, nickname: result.nickname })); // nickname, email 받아서 Redux에 저장
setUserId(result.email); // GA4 User-ID 설정

// 새로고침에도 유지하고 싶다면 localStorage에도 저장
// localStorage.setItem('nickname', result.nickname);
Expand Down