由服务器决定冷却时间
真正的限流由服务器执行。让服务器告诉客户端需要等待多久。
在 onResend 中返回 retryAfter
<Cooldown.Root
storageKey={`otp:${email}`}
duration={30}
onResend={async () => {
const res = await fetch('/api/otp/resend', {
method: 'POST',
body: JSON.stringify({ email }),
})
if (res.status === 429) {
return { retryAfter: Number(res.headers.get('Retry-After') ?? 30) }
}
if (!res.ok) throw new Error('验证码发送失败')
const { nextAllowedAt } = await res.json()
return { endsAt: nextAllowedAt }
}}
/>- 没有返回值:使用
duration。 { retryAfter }:从现在起的秒数。{ endsAt }:毫秒级时间戳。- 抛出错误:状态变为
error。不计入尝试次数,用户可以立即重试。
不发送也能开始计时
如果第一条验证码是由其他请求发送的(比如注册表单),可以自己开始冷却:
const cd = useCooldown({ storageKey: `otp:${email}` })
const { retryAfter } = await api.signup(form)
cd.start({ retryAfter })start({ countAttempt: false }) 会延长当前冷却,但不消耗尝试次数。