kgroad-frontend2/src/widgets/tables/ProfileTable/profile-reports.store.ts
2024-03-10 04:38:46 +06:00

83 lines
2.1 KiB
TypeScript

import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import {
IMyReports,
IMyReportsList,
} from "@/shared/types/my-reports";
import { AxiosError } from "axios";
import { create } from "zustand";
const filterCategories: Record<string, string> = {
count_reviews: "count_reviews",
total_likes: "total_likes",
};
interface IProfileReportsStore extends IFetch {
data: IMyReportsList;
getMyReports: (
filter: string,
page: number,
access_token: string
) => void;
}
export const useProfileReportsStore = create<IProfileReportsStore>(
(set) => ({
isLoading: false,
error: "",
data: {
count: 0,
previous: null,
next: null,
results: [],
},
getMyReports: async (
sort: string,
page: number,
access_token: string
) => {
try {
const Authorization = `Bearer ${access_token}`;
const config = {
headers: {
Authorization,
},
};
set({ isLoading: true });
const data = await apiInstance
.get<IMyReportsList>(
`/users/reports/?page=${page}&page_size=8`,
config
)
.then((res) => res.data);
if (sort === "date") {
data.results = data.results.sort((a, b) => {
const dateA = new Date(b.created_at) as unknown as number;
const dateB = new Date(a.created_at) as unknown as number;
return dateA - dateB;
});
} else if (sort === "reviews") {
data.results = data.results.sort(
(a, b) => b.count_reviews - a.count_reviews
);
} else if (sort === "rating") {
data.results = data.results.sort(
(a, b) => b.total_likes - a.total_likes
);
}
set({ data: data });
} catch (error: unknown) {
if (error instanceof AxiosError) {
set({ error: error.message });
} else {
set({ error: "an error ocured" });
}
} finally {
set({ isLoading: false });
}
},
})
);