kgroad-frontend2/src/widgets/RatingSection/ratingSectionStore.ts
2024-02-19 15:14:19 +06:00

101 lines
2.7 KiB
TypeScript

import { apiInstance } from "@/shared/config/apiConfig";
import { IFetch } from "@/shared/types/fetch-type";
import { IList } from "@/shared/types/list-type";
import { IReport } from "@/shared/types/report-type";
import { create } from "zustand";
interface IFetchReports extends IList {
results: IReport[];
}
interface IRatingStore extends IFetch {
data: IFetchReports;
getReports: (
categories: string,
page: number,
filter: { option: string; toggle: boolean }
) => Promise<void>;
}
export const useRatingStore = create<IRatingStore>((set) => ({
data: {
count: 0,
previous: null,
next: null,
results: [],
},
isLoading: false,
error: "",
getReports: async (
query: string = "",
page: number = 1,
filter: { option: string; toggle: boolean }
) => {
try {
set({ isLoading: true });
const data = (
await apiInstance.get<IFetchReports>(
`/report/?page=${page}&page_size=${8}`
)
).data;
const searched = data.results.filter((rating) => {
return rating.location.some((location) => {
return location.address
.toLowerCase()
.includes(query.toLowerCase());
});
});
data.results = [...searched];
if (filter.option === "date" && filter.toggle === false) {
data.results = data.results.sort((a, b) => {
const dateA = new Date(a.created_at) as unknown as number;
const dateB = new Date(b.created_at) as unknown as number;
return dateA - dateB;
});
} else if (filter.option === "date" && filter.toggle === true) {
data.results = data.results.sort((a, b) => {
const dateA = new Date(a.created_at) as unknown as number;
const dateB = new Date(b.created_at) as unknown as number;
return dateB - dateA;
});
}
if (filter.option === "reviews" && filter.toggle === false) {
data.results = data.results.sort(
(a, b) => a.count_reviews - b.count_reviews
);
} else if (
filter.option === "reviews" &&
filter.toggle === true
) {
data.results = data.results.sort(
(a, b) => b.count_reviews - a.count_reviews
);
}
if (filter.option === "rating" && filter.toggle === false) {
data.results = data.results.sort(
(a, b) => a.total_likes - b.total_likes
);
} else if (
filter.option === "rating" &&
filter.toggle === true
) {
data.results = data.results.sort(
(a, b) => b.total_likes - a.total_likes
);
}
set({ data: data });
} catch (error: any) {
set({ error: error.message });
} finally {
set({ isLoading: false });
}
},
}));