Skip to content

Commit 9b2fbc8

Browse files
committed
Clean up excessive console.log statements
- Remove debug logs from TotalEarning.tsx - Remove chart data logs from TotalEarningChart.tsx - Remove API response logs from activity.api.ts - Remove extensive debug logs from useChartData.ts - Remove component logs from PaidSubscribers.tsx - Fix unused variables after log removal
1 parent 5208326 commit 9b2fbc8

6 files changed

Lines changed: 82 additions & 75 deletions

File tree

src/api/activity.api.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,6 @@ export const getUserActivities = (handleLogout: () => void): Promise<WalletTrans
4040
return [];
4141
}
4242
// Assuming your backend response matches the WalletTransaction interface
43-
// eslint-disable-next-line
44-
console.log("User Activity Data: ", data)
4543
return data.map((item: any) => ({
4644
id: item.ID,
4745
witness_tx_id: item.Address,

src/components/relay-dashboard/paid-subscribers/PaidSubscribers.tsx

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import { CreatorButton } from './avatar/SubscriberAvatar.styles';
2121
const { Text } = Typography;
2222

2323
export const PaidSubscribers: React.FC = () => {
24-
console.log('[PaidSubscribers] Component rendering...');
2524
const hookResult = usePaidSubscribers(12);
2625
const { subscribers, fetchMore, hasMore, loading, useDummyData } = hookResult;
2726
const ndkInstance = useNDK();
@@ -76,7 +75,6 @@ export const PaidSubscribers: React.FC = () => {
7675
setAllSubscribers([...subscribers]); // Start with current subscribers
7776

7877
// Fetch more subscribers if available
79-
const currentSubscribers = [...subscribers];
8078
let canFetchMore = hasMore;
8179

8280
while (canFetchMore) {
@@ -86,7 +84,6 @@ export const PaidSubscribers: React.FC = () => {
8684
// track the updated state properly or use a separate hook for fetching all
8785
canFetchMore = false; // For now, just fetch once more
8886
} catch (error) {
89-
console.error('Error fetching more subscribers:', error);
9087
break;
9188
}
9289
}
@@ -95,19 +92,16 @@ export const PaidSubscribers: React.FC = () => {
9592
useEffect(() => {
9693
// Implement hybrid profile fetching: NDK first, fallback to backend data
9794
if (useDummyData) {
98-
console.warn('[PaidSubscribers] Using dummy data, skipping profile fetch');
9995
setLoadingProfiles(false);
10096
return;
10197
}
10298

10399
const fetchProfiles = async () => {
104100
if (!ndkInstance || !ndkInstance.ndk) {
105-
console.error('[PaidSubscribers] NDK instance is not initialized, using backend data only');
106101
setLoadingProfiles(false);
107102
return;
108103
}
109104

110-
console.log('[PaidSubscribers] Starting hybrid profile fetch for', subscribers.length, 'subscribers');
111105

112106
// Process each subscriber with hybrid approach
113107
await Promise.all(
@@ -121,37 +115,21 @@ export const PaidSubscribers: React.FC = () => {
121115
);
122116

123117
if (hasValidProfile) {
124-
console.log(`[PaidSubscribers] Profile already cached for ${subscriber.pubkey}:`, {
125-
name: existingProfile.name,
126-
picture: !!existingProfile.picture,
127-
about: !!existingProfile.about
128-
});
129118
return;
130119
}
131120

132121
try {
133-
console.log(`[PaidSubscribers] Fetching NDK profile for ${subscriber.pubkey}`);
134122

135123
// Try to fetch profile from NDK (user's relay + other relays)
136124
const user = await ndkInstance.ndk?.getUser({ pubkey: subscriber.pubkey }).fetchProfile();
137125

138126
if (user && (user.name || user.picture || user.about)) {
139127
// NDK returned a profile - use it as the primary source
140-
console.log(`[PaidSubscribers] NDK profile found for ${subscriber.pubkey}:`, {
141-
name: user.name,
142-
picture: user.picture,
143-
about: user.about
144-
});
145128

146129
const ndkProfile = convertNDKUserProfileToSubscriberProfile(subscriber.pubkey, user);
147130
updateSubscriberProfile(subscriber.pubkey, ndkProfile);
148131
} else {
149132
// NDK came up empty - fallback to backend data
150-
console.log(`[PaidSubscribers] NDK profile empty for ${subscriber.pubkey}, falling back to backend data:`, {
151-
name: subscriber.name,
152-
picture: subscriber.picture,
153-
about: subscriber.about
154-
});
155133

156134
// Use the backend data as-is since NDK had no better information
157135
updateSubscriberProfile(subscriber.pubkey, {
@@ -163,10 +141,8 @@ export const PaidSubscribers: React.FC = () => {
163141
});
164142
}
165143
} catch (error) {
166-
console.error(`[PaidSubscribers] Error fetching NDK profile for ${subscriber.pubkey}:`, error);
167144

168145
// Error occurred - fallback to backend data
169-
console.log(`[PaidSubscribers] NDK error for ${subscriber.pubkey}, using backend data`);
170146
updateSubscriberProfile(subscriber.pubkey, {
171147
...subscriber,
172148
name: subscriber.name || 'Anonymous Subscriber',
@@ -177,7 +153,6 @@ export const PaidSubscribers: React.FC = () => {
177153
}),
178154
);
179155

180-
console.log('[PaidSubscribers] Hybrid profile fetch completed');
181156
setLoadingProfiles(false);
182157
};
183158

@@ -190,8 +165,6 @@ export const PaidSubscribers: React.FC = () => {
190165
setIsViewAllModalVisible(false);
191166
};
192167

193-
console.log('[PaidSubscribers] Received subscribers:', subscribers);
194-
console.log('[PaidSubscribers] Complete hook result:', hookResult);
195168

196169
const sliderRef = useRef<Splide>(null);
197170
const { isTablet: isTabletOrHigher } = useResponsive();

src/components/relay-dashboard/totalEarning/TotalEarning.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ export const TotalEarning: React.FC = () => {
3333
const isIncreased = latestRate && previousRate ? latestRate > previousRate : false;
3434
const rateDifference = latestRate && previousRate ? ((latestRate - previousRate) / previousRate) * 100 : 0;
3535

36-
console.log(`latestRate: ${latestRate} previousRate: ${previousRate}`);
37-
console.log(`Rate difference: ${rateDifference}`);
3836

3937
if (isLoading) {
4038
return <div>{t('common.loading')}</div>;

src/components/relay-dashboard/totalEarning/TotalEarningChart/TotalEarningChart.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ export const TotalEarningChart: React.FC<TotalEarningChartProps> = ({ xAxisData,
2020
const theme = useAppSelector((state) => state.theme.theme);
2121
const { t } = useTranslation();
2222

23-
console.log('xAxisData:', xAxisData);
24-
console.log('earningData:', earningData);
2523

2624
// Ensure all values are numbers and handle empty arrays
2725
const numericData = earningData.data.map(val => Number(val)).filter(val => !isNaN(val));

src/hooks/useBitcoinRates.ts

Lines changed: 82 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ interface Earning {
88
usd_value: number;
99
}
1010

11+
// Global cache to prevent multiple simultaneous requests
12+
let globalRatesCache: { data: Earning[]; timestamp: number } | null = null;
13+
let globalPromise: Promise<Earning[]> | null = null;
14+
const CACHE_DURATION = 480000; // 8 minutes (backend updates every 10 minutes)
15+
1116
export const useBitcoinRates = () => {
1217
const [rates, setRates] = useState<Earning[]>([]);
1318
const [isLoading, setIsLoading] = useState(true);
@@ -16,47 +21,96 @@ export const useBitcoinRates = () => {
1621
const handleLogout = useHandleLogout();
1722

1823
useEffect(() => {
19-
const fetchBitcoinRates = async () => {
20-
setIsLoading(true);
21-
setError(null); // Reset error state before fetching
24+
const fetchBitcoinRates = async (retryCount = 0): Promise<Earning[]> => {
25+
// Check cache first
26+
if (globalRatesCache && Date.now() - globalRatesCache.timestamp < CACHE_DURATION) {
27+
const cacheAge = Math.round((Date.now() - globalRatesCache.timestamp) / 1000);
28+
console.log(`[useBitcoinRates] Using cached data (age: ${cacheAge}s)`);
29+
return globalRatesCache.data;
30+
}
2231

23-
try {
24-
const token = readToken(); // Read JWT from localStorage
25-
if (!token) {
26-
throw new Error('No authentication token found');
27-
}
32+
// If there's already a request in progress, wait for it
33+
if (globalPromise) {
34+
console.log('[useBitcoinRates] Waiting for existing request to complete...');
35+
return globalPromise;
36+
}
2837

29-
const response = await fetch(`${config.baseURL}/api/bitcoin-rates/last-30-days`, {
30-
method: 'GET',
31-
headers: {
32-
'Content-Type': 'application/json',
33-
'Authorization': `Bearer ${token}`, // Attach the JWT token to the request
34-
},
35-
});
36-
37-
if (!response.ok) {
38-
if (response.status === 401) {
39-
handleLogout(); // Log out the user if token is invalid or expired
40-
throw new Error('Authentication failed. You have been logged out.');
38+
// Create new request
39+
globalPromise = new Promise<Earning[]>(async (resolve, reject) => {
40+
try {
41+
const token = readToken(); // Read JWT from localStorage
42+
if (!token) {
43+
throw new Error('No authentication token found');
44+
}
45+
46+
console.log('[useBitcoinRates] Fetching bitcoin rates...');
47+
const response = await fetch(`${config.baseURL}/api/bitcoin-rates/last-30-days`, {
48+
method: 'GET',
49+
headers: {
50+
'Content-Type': 'application/json',
51+
'Authorization': `Bearer ${token}`, // Attach the JWT token to the request
52+
},
53+
});
54+
55+
console.log(`[useBitcoinRates] Response status: ${response.status}`);
56+
57+
if (!response.ok) {
58+
if (response.status === 401) {
59+
handleLogout(); // Log out the user if token is invalid or expired
60+
throw new Error('Authentication failed. You have been logged out.');
61+
}
62+
throw new Error(`Network response was not ok (status: ${response.status})`);
4163
}
42-
throw new Error(`Network response was not ok (status: ${response.status})`);
43-
}
4464

45-
const data = await response.json();
46-
setRates(
47-
data.map((item: { Rate: number; TimestampHornets: string }) => ({
65+
const data = await response.json();
66+
console.log('[useBitcoinRates] Data received successfully');
67+
const processedData = data.map((item: { Rate: number; TimestampHornets: string }) => ({
4868
date: new Date(item.TimestampHornets).getTime(),
4969
usd_value: item.Rate,
50-
})),
51-
);
70+
}));
71+
72+
// Cache the result
73+
globalRatesCache = {
74+
data: processedData,
75+
timestamp: Date.now(),
76+
};
77+
78+
resolve(processedData);
79+
} catch (err: any) {
80+
// Retry on network errors but not on auth errors
81+
if (retryCount < 2 && err.message.includes('network') && !err.message.includes('Authentication')) {
82+
setTimeout(() => {
83+
globalPromise = null; // Clear the promise so retry can start
84+
fetchBitcoinRates(retryCount + 1).then(resolve).catch(reject);
85+
}, 1000);
86+
return;
87+
}
88+
89+
reject(err);
90+
} finally {
91+
globalPromise = null; // Clear the promise when done
92+
}
93+
});
94+
95+
return globalPromise;
96+
};
97+
98+
const loadRates = async () => {
99+
setIsLoading(true);
100+
setError(null);
101+
102+
try {
103+
const data = await fetchBitcoinRates();
104+
setRates(data);
52105
} catch (err: any) {
106+
console.error('[useBitcoinRates] Error fetching rates:', err);
53107
setError(err.message);
54108
} finally {
55109
setIsLoading(false);
56110
}
57111
};
58112

59-
fetchBitcoinRates();
113+
loadRates();
60114
}, [handleLogout]);
61115

62116
return { rates, isLoading, error };

src/hooks/useChartData.ts

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -46,28 +46,19 @@ const useChartData = () => {
4646

4747
const data: FileCountResponse = await response.json();
4848

49-
// Log the complete backend response for debugging
50-
console.log('=== CHART DATA BACKEND RESPONSE ===');
51-
console.log('Full response:', JSON.stringify(data, null, 2));
52-
console.log('Response keys:', Object.keys(data));
53-
console.log('==============================');
5449

5550
// Process the data into chartDataItems using translated names
5651
// Handle dynamic media types while maintaining UI compatibility
5752
const newChartData: ChartDataItem[] = [];
5853

5954
// Always include kinds first
60-
console.log('Adding kinds data:', { value: data.kinds, name: t('categories.kinds') });
6155
newChartData.push({ value: data.kinds, name: t('categories.kinds') });
6256

6357
// Destructure to separate kinds from media types
6458
const { kinds, ...mediaCounts } = data;
65-
console.log('Media counts after destructuring:', mediaCounts);
66-
console.log('Media count entries:', Object.entries(mediaCounts));
6759

6860
// Map dynamic media types to chart data with fallback translations
6961
Object.entries(mediaCounts).forEach(([mediaType, count]) => {
70-
console.log(`Processing media type: ${mediaType} with count: ${count}`);
7162
let translationKey = '';
7263
let fallbackName = '';
7364

@@ -99,14 +90,9 @@ const useChartData = () => {
9990
// Use translation if available, otherwise use fallback
10091
const displayName = t(translationKey, { defaultValue: fallbackName });
10192
const chartItem = { value: count, name: displayName };
102-
console.log(`Adding chart item:`, chartItem);
10393
newChartData.push(chartItem);
10494
});
10595

106-
console.log('=== FINAL CHART DATA ===');
107-
console.log('Final chart data:', newChartData);
108-
console.log('Chart data length:', newChartData.length);
109-
console.log('========================');
11096

11197
setChartData(newChartData);
11298
} catch (error) {

0 commit comments

Comments
 (0)