fixed show phone number
This commit is contained in:
42
src/hooks/useRevealPhone.js
Normal file
42
src/hooks/useRevealPhone.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { revealPhone } from "../api/phoneApi";
|
||||
import { describeApiError } from "../api/apiErrors";
|
||||
|
||||
/**
|
||||
* useRevealPhone — кнопка «Показать номер» в карточке объявления.
|
||||
* Браузер решает proof-of-work задачу (доли секунды) и получает номер.
|
||||
*
|
||||
* @param {number|string} postId
|
||||
* @returns {{ phone: string, loading: boolean, error: string, reveal: function, clearError: function }}
|
||||
*/
|
||||
export function useRevealPhone(postId) {
|
||||
const { t } = useTranslation();
|
||||
const [phone, setPhone] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const abortRef = useRef(null);
|
||||
|
||||
// Карточка ушла из ленты — перебор и запросы больше не нужны
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
const reveal = useCallback(async () => {
|
||||
if (loading || phone) return;
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
setPhone(await revealPhone(postId, { signal: controller.signal }));
|
||||
} catch (err) {
|
||||
if (err?.name === "AbortError") return;
|
||||
setError(describeApiError(err, t("postCard.phoneError")));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
}, [loading, phone, postId, t]);
|
||||
|
||||
const clearError = useCallback(() => setError(""), []);
|
||||
|
||||
return { phone, loading, error, reveal, clearError };
|
||||
}
|
||||
Reference in New Issue
Block a user