fixed code
This commit is contained in:
46
src/hooks/useContactSeller.js
Normal file
46
src/hooks/useContactSeller.js
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useChats } from "./useChats";
|
||||
|
||||
/**
|
||||
* useContactSeller — общая логика открытия/создания чата с автором объявления.
|
||||
* Используется в PostOnFeed (карточка в ленте) и ImageViewer (просмотр фото).
|
||||
*
|
||||
* @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, {
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user