fixed code
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { useCallback } from 'react';
|
||||
// src/hooks/useFavorites.js
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API_URL } from '../config/authConstants';
|
||||
import { apiFetch } from '../api/apiClient';
|
||||
|
||||
@@ -7,51 +9,59 @@ import { apiFetch } from '../api/apiClient';
|
||||
* Использует backend API для добавления/удаления лайков.
|
||||
*/
|
||||
export function useFavorites() {
|
||||
const { t } = useTranslation();
|
||||
const [error, setError] = useState("");
|
||||
|
||||
/**
|
||||
* Переключает лайк на посте через API.
|
||||
* @param {number} postId - ID поста
|
||||
* @returns {Promise<boolean>} - true если операция успешна
|
||||
* @returns {Promise<{success: boolean, error: string|null}>}
|
||||
*/
|
||||
const toggleFavorite = useCallback(async (postId) => {
|
||||
setError("");
|
||||
try {
|
||||
const response = await apiFetch(`${API_URL}/api/v1/favorites/${postId}/toggle`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to toggle favorite: ${response.status}`);
|
||||
throw new Error(t('favorites.toggleError'));
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite:', error);
|
||||
return false;
|
||||
return { success: true, error: null };
|
||||
} catch (err) {
|
||||
console.error('Error toggling favorite:', err);
|
||||
const message = err.message || t('favorites.toggleError');
|
||||
setError(message);
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}, []);
|
||||
}, [t]);
|
||||
|
||||
/**
|
||||
* Загружает список лайкнутых постов текущего пользователя.
|
||||
* @returns {Promise<Array>} - массив ID лайкнутых постов
|
||||
*/
|
||||
const loadFavorites = useCallback(async () => {
|
||||
setError("");
|
||||
try {
|
||||
const response = await apiFetch(`${API_URL}/api/v1/favorites`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load favorites: ${response.status}`);
|
||||
throw new Error(t('favorites.loadError'));
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// API возвращает массив постов, извлекаем ID
|
||||
return Array.isArray(data) ? data.map(post => post.id) : [];
|
||||
} catch (error) {
|
||||
console.error('Error loading favorites:', error);
|
||||
} catch (err) {
|
||||
console.error('Error loading favorites:', err);
|
||||
setError(err.message || t('favorites.loadError'));
|
||||
return [];
|
||||
}
|
||||
}, []);
|
||||
}, [t]);
|
||||
|
||||
return {
|
||||
toggleFavorite,
|
||||
loadFavorites,
|
||||
error,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user