Skip to content

Commit

Permalink
perf(popup/Home): debounce setting rate of pay
Browse files Browse the repository at this point in the history
  • Loading branch information
sidvishnoi committed May 16, 2024
1 parent c1afa2b commit 0843057
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/popup/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import React from 'react'
import { PopupStateContext, ReducerActionType } from '@/popup/lib/context'
import { WarningSign } from '@/popup/components/Icons'
import { Slider } from '../components/ui/Slider'
import { updateRateOfPay } from '../lib/messages'
import { updateRateOfPay as updateRateOfPay_ } from '../lib/messages'
import { Label } from '../components/ui/Label'
import { getCurrencySymbol, roundWithPrecision } from '../lib/utils'
import { debounceAsync } from '@/shared/helpers'
import { PayWebsiteForm } from '../components/PayWebsiteForm'

const updateRateOfPay = debounceAsync(updateRateOfPay_, 500);

export const Component = () => {
const {
state: {
Expand All @@ -29,19 +32,18 @@ export const Component = () => {
return r.toExponential()
}, [rateOfPay, walletAddress.assetScale])

// TODO: Use a debounce
const onRateChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const rateOfPay = event.currentTarget.value
const response = await updateRateOfPay({
rateOfPay
})
if (!response.success) return
dispatch({
type: ReducerActionType.UPDATE_RATE_OF_PAY,
data: {
rateOfPay
}
})
const response = await updateRateOfPay({ rateOfPay })
if (!response.success) {
// TODO: Maybe reset to old state, but not while user is active (avoid jank)
}
}

return (
Expand Down
16 changes: 16 additions & 0 deletions src/shared/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,19 @@ export const notNullOrUndef = <T>(
return t
}
}

export function debounceAsync<T extends unknown[], R extends Promise<unknown>>(
func: (...args: T) => R,
wait: number
) {
let timeout: ReturnType<typeof setTimeout> | null = null
return function (...args: T) {
return new Promise<Awaited<R>>((resolve) => {
if (timeout != null) clearTimeout(timeout)
timeout = setTimeout(() => {
timeout = null
void Promise.resolve(func(...args)).then(resolve)
}, wait)
})
}
}

0 comments on commit 0843057

Please sign in to comment.