added refresh token

This commit is contained in:
SlimusMinus
2026-08-03 02:44:57 +03:00
parent b6c61c72d9
commit abbcc330e7
16 changed files with 210 additions and 135 deletions

View File

@@ -1,14 +1,8 @@
import { useState, useCallback } from "react";
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
function authHeaders() {
return {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("token")}`,
};
}
export function useChats() {
const [chats, setChats] = useState([]);
const [loading, setLoading] = useState(false);
@@ -16,7 +10,7 @@ export function useChats() {
const fetchChats = useCallback(async () => {
setLoading(true);
try {
const res = await fetch(`${API_URL}/api/v1/chats`, { headers: authHeaders() });
const res = await apiFetch(`${API_URL}/api/v1/chats`);
const data = await res.json();
// API may return an array directly or a wrapper object like { items: [] } / { content: [] }
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
@@ -31,7 +25,7 @@ export function useChats() {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}`);
if (postId) url.searchParams.set("postId", postId);
const res = await fetch(url, { method: "POST", headers: authHeaders() });
const res = await apiFetch(url, { method: "POST" });
if (!res.ok) throw new Error("Не удалось создать чат");
const chat = await res.json();
if (postInfo && chat.id) {
@@ -41,7 +35,7 @@ export function useChats() {
}, []);
const fetchMessages = useCallback(async (chatId) => {
const res = await fetch(`${API_URL}/api/v1/chats/${chatId}/messages`, { headers: authHeaders() });
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
const data = await res.json();
// Normalize: array or wrapper object
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
@@ -49,9 +43,8 @@ export function useChats() {
const markAsRead = useCallback(async (chatId) => {
try {
await fetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
headers: authHeaders(),
});
} catch (e) {
console.error("Failed to mark as read:", e);
@@ -59,4 +52,4 @@ export function useChats() {
}, []);
return { chats, loading, fetchChats, createOrGetChat, fetchMessages, markAsRead };
}
}