added files in git
This commit is contained in:
74
src/hooks/useFavorites.js
Normal file
74
src/hooks/useFavorites.js
Normal file
@@ -0,0 +1,74 @@
|
||||
import { useCallback } from 'react';
|
||||
import { API_URL } from '../config/authConstants';
|
||||
|
||||
/**
|
||||
* Хук для работы с лайками (избранное).
|
||||
* Использует backend API для добавления/удаления лайков.
|
||||
*/
|
||||
export function useFavorites() {
|
||||
/**
|
||||
* Переключает лайк на посте через API.
|
||||
* @param {number} postId - ID поста
|
||||
* @param {string} token - JWT токен авторизации
|
||||
* @returns {Promise<boolean>} - true если операция успешна
|
||||
*/
|
||||
const toggleFavorite = useCallback(async (postId, token) => {
|
||||
if (!token) {
|
||||
console.warn('Cannot toggle favorite: no token');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/v1/favorites/${postId}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to toggle favorite: ${response.status}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error toggling favorite:', error);
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Загружает список лайкнутых постов текущего пользователя.
|
||||
* @param {string} token - JWT токен авторизации
|
||||
* @returns {Promise<Array>} - массив ID лайкнутых постов
|
||||
*/
|
||||
const loadFavorites = useCallback(async (token) => {
|
||||
if (!token) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/v1/favorites`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load favorites: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// API возвращает массив постов, извлекаем ID
|
||||
return Array.isArray(data) ? data.map(post => post.id) : [];
|
||||
} catch (error) {
|
||||
console.error('Error loading favorites:', error);
|
||||
return [];
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
toggleFavorite,
|
||||
loadFavorites,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user