Files
nahodka-front/src/hooks/useContactSeller.js
2026-10-09 01:21:14 +03:00

47 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from 'react-i18next';
import { useChats } from "./useChats";
/**
* useContactSeller — общая логика открытия/создания чата с автором объявления.
* Используется в PostOnFeed (карточка в ленте).
*
* @param {object} post — объявление: { id, userId, title, images, emoji }
* @returns {{
* contactSeller: (onBeforeNavigate?: function) => Promise<void>,
* error: string,
* clearError: function
* }}
*/
export function useContactSeller(post) {
const { t } = useTranslation();
const [error, setError] = useState("");
const navigate = useNavigate();
const { createOrGetChat } = useChats();
/**
* @param {function} [onBeforeNavigate] — вызывается перед переходом в чат
* (например, чтобы закрыть модалку просмотра фото до навигации)
*/
const contactSeller = useCallback(async (onBeforeNavigate) => {
if (!post) return;
try {
const chat = await createOrGetChat(post.userId, post.id, {
id: post.id,
title: post.title,
images: post.images,
emoji: post.emoji,
});
onBeforeNavigate?.();
navigate(`/chats/${chat.id}`);
} catch (err) {
console.error(err);
setError(t('postCard.contactError'));
}
}, [post, createOrGetChat, navigate, t]);
const clearError = useCallback(() => setError(""), []);
return { contactSeller, error, clearError };
}