fix: improve caching and prevent duplicate fetches in AccountView (#5883)

* fix:  improve caching and prevent duplicate fetches in AccountView

- Wrap cacheCurrentData in useCallback with proper dependencies
- Add initialFetchCompleteRef to track mount fetch completion
- Improve organization change handling to prevent race conditions
- Remove biome-ignore comments for exhaustive dependencies
- Replace mb-[5px] with mb-1.5 for consistent Tailwind spacing

* changeset added
This commit is contained in:
Bee authored and GitHub committed 2025-08-29 11:18:55 -07:00
1 parent c6aa47095e
commit 45871a962e
2 files changed
+73 -34

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix issue on Account view where balance is fetched twice that cause janky UI
@@ -41,7 +41,7 @@ const AccountView = ({ onDone, clineUser, organizations, activeOrganization }: A
<VSCodeButton onClick={onDone}>Done</VSCodeButton>
</div>
<div className="flex-grow overflow-hidden pr-[8px] flex flex-col">
<div className="h-full mb-[5px]">
<div className="h-full mb-1.5">
{clineUser?.uid ? (
<ClineAccountView
activeOrganization={activeOrganization}
@@ -89,20 +89,25 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
}, [])
// Simple cache function without dependencies
const cacheCurrentData = (id: string) => {
dataCache.current.set(id, {
balance,
usageData,
paymentsData,
lastFetchTime,
})
}
const cacheCurrentData = useCallback(
(id: string) => {
dataCache.current.set(id, {
balance,
usageData,
paymentsData,
lastFetchTime,
})
},
[balance, usageData, paymentsData, lastFetchTime],
)
// Track the active organization ID to detect changes
const [lastActiveOrgId, setLastActiveOrgId] = useState<string | undefined>(activeOrganization?.organizationId)
// Use ref for debounce timeout to avoid re-renders
const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null)
// Track if manual fetch is in progress to avoid duplicate fetches
const manualFetchInProgressRef = useRef<boolean>(false)
// Track if initial mount fetch has completed to avoid duplicate fetches
const initialFetchCompleteRef = useRef<boolean>(false)
const fetchUserCredit = useCallback(async () => {
try {
@@ -119,7 +124,6 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
}
}, [])
// biome-ignore lint/correctness/useExhaustiveDependencies: <cacheCurrentData changes on every re-render>
const fetchCreditBalance = useCallback(
async (id: string, skipCache = false) => {
try {
@@ -159,7 +163,6 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
[isLoading, uid, fetchUserCredit, loadCachedData],
)
// biome-ignore lint/correctness/useExhaustiveDependencies: <cacheCurrentData changes on every re-render>
const handleOrganizationChange = useCallback(
async (event: any) => {
const target = event.target as HTMLSelectElement
@@ -169,26 +172,43 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
const newValue = target.value
if (newValue !== dropdownValue) {
// Clear any pending debounced fetch since we're doing a manual one
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current)
debounceTimeoutRef.current = null
}
// Cache current data before switching
cacheCurrentData(dropdownValue)
setDropdownValue(newValue)
// Load cached data for new selection immediately, or clear if no cache
// Only clear if we don't have cached data to avoid unnecessary flashing
if (!loadCachedData(newValue)) {
// No cached data - clear current state to avoid showing wrong data
setBalance(null)
setUsageData([])
setPaymentsData([])
}
// Set flag to indicate manual fetch in progress
manualFetchInProgressRef.current = true
// Fetch the new data
await fetchCreditBalance(newValue)
// Update the last active org ID to prevent the effect from triggering
setLastActiveOrgId(newValue === uid ? undefined : newValue)
// Send the change to the server
const organizationId = newValue === uid ? undefined : newValue
await AccountServiceClient.setUserOrganization({ organizationId })
// Clear the manual fetch flag after everything is done
manualFetchInProgressRef.current = false
}
// Set flag to indicate manual fetch in progress
manualFetchInProgressRef.current = true
await fetchCreditBalance(newValue)
manualFetchInProgressRef.current = false
// Send the change to the server
const organizationId = newValue === uid ? undefined : newValue
AccountServiceClient.setUserOrganization({ organizationId })
},
[uid, dropdownValue, loadCachedData],
[uid, dropdownValue, loadCachedData, fetchCreditBalance, cacheCurrentData],
)
// Fetch balance every 60 seconds
@@ -199,33 +219,39 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
const clineUrl = appBaseUrl || "https://app.cline.bot"
// Fetch balance on mount
// biome-ignore lint/correctness/useExhaustiveDependencies: <Only run once on mount>
useEffect(() => {
async function initialFetch() {
await fetchCreditBalance(dropdownValue)
initialFetchCompleteRef.current = true
}
initialFetch()
}, [])
// biome-ignore lint/correctness/useExhaustiveDependencies: <cacheCurrentData changes on every re-render>
useEffect(() => {
// Handle organization changes with 500ms debounce
const currentActiveOrgId = activeOrganization?.organizationId
const hasDropdownChanged = dropdownValue !== (currentActiveOrgId || uid)
const hasActiveOrgChanged = currentActiveOrgId !== lastActiveOrgId
if (hasDropdownChanged || hasActiveOrgChanged) {
// Only handle external organization changes (not dropdown changes)
// Dropdown changes are handled by handleOrganizationChange
const isExternalOrgChange = hasActiveOrgChanged && !manualFetchInProgressRef.current
if (isExternalOrgChange) {
// Clear any existing timeout
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current)
}
// If dropdown changed, load cached data for the current dropdown value
if (hasDropdownChanged) {
// Cache the previous data first
cacheCurrentData(lastActiveOrgId || uid)
// Load cached data for current dropdown value, or clear if no cache
if (!loadCachedData(dropdownValue)) {
// Update dropdown to match the new active organization
const newDropdownValue = currentActiveOrgId || uid
if (newDropdownValue !== dropdownValue) {
// Cache current data before switching
cacheCurrentData(dropdownValue)
setDropdownValue(newDropdownValue)
// Load cached data for new selection immediately, or clear if no cache
// Only clear data if initial fetch has completed to avoid clearing on mount
if (!loadCachedData(newDropdownValue) && initialFetchCompleteRef.current) {
// No cached data - clear to avoid showing wrong data
setBalance(null)
setUsageData([])
@@ -233,15 +259,15 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
}
}
// Only set timeout if manual fetch is not in progress
if (!manualFetchInProgressRef.current) {
// Only set timeout if initial fetch is complete
if (initialFetchCompleteRef.current) {
// Set new timeout to fetch after 500ms
debounceTimeoutRef.current = setTimeout(() => {
fetchCreditBalance(dropdownValue)
fetchCreditBalance(newDropdownValue)
setLastActiveOrgId(currentActiveOrgId)
}, 500)
} else {
// Manual fetch is handling this, just update the active org ID
// Just update the active org ID
setLastActiveOrgId(currentActiveOrgId)
}
}
@@ -252,7 +278,15 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
clearTimeout(debounceTimeoutRef.current)
}
}
}, [dropdownValue, activeOrganization?.organizationId, lastActiveOrgId, uid])
}, [
activeOrganization?.organizationId,
lastActiveOrgId,
uid,
dropdownValue,
loadCachedData,
fetchCreditBalance,
cacheCurrentData,
])
return (
<div className="h-full flex flex-col">