114 lines
2.5 KiB
TypeScript
114 lines
2.5 KiB
TypeScript
|
|
import {useEffect, useState} from "react";
|
||
|
|
import {DEBUG_MODE} from "../utils/common";
|
||
|
|
import {ApiResponse, PageResponse} from "../types/api.ts";
|
||
|
|
import {PageControl} from "../types/common.ts";
|
||
|
|
|
||
|
|
export function hostUrl(url: string){
|
||
|
|
return DEBUG_MODE? "http://localhost:8000"+url: url;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function apiUrl(url: string) {
|
||
|
|
return hostUrl("/api/v1"+url);
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
export async function getFetch(path:string) {
|
||
|
|
|
||
|
|
try{
|
||
|
|
const response = await fetch(
|
||
|
|
apiUrl(path), {
|
||
|
|
method: "GET",
|
||
|
|
credentials: "include"
|
||
|
|
}
|
||
|
|
);
|
||
|
|
|
||
|
|
if (!response.ok){
|
||
|
|
const body = await response.json();
|
||
|
|
|
||
|
|
console.error('Error fetching:', 'Network response was not ok', body);
|
||
|
|
|
||
|
|
return {
|
||
|
|
body: body,
|
||
|
|
success: false
|
||
|
|
} as ApiResponse;
|
||
|
|
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
body: await response.json(),
|
||
|
|
success: true,
|
||
|
|
} as ApiResponse
|
||
|
|
}
|
||
|
|
|
||
|
|
catch {
|
||
|
|
return {
|
||
|
|
success: false
|
||
|
|
} as ApiResponse;
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
export function useDataPage<T>(application:string, endpoint: string) {
|
||
|
|
const [data, setData] = useState<T[]|null>(null);
|
||
|
|
// const [previousUrl, setPreviousUrl] = useState<string|undefined>(undefined)
|
||
|
|
// const [nextUrl, setNextUrl] = useState<string|undefined>(undefined)
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
useEffect(
|
||
|
|
()=>{
|
||
|
|
if (data === null){
|
||
|
|
getFetch(`/${application}/${endpoint}/`).then((r)=>{
|
||
|
|
if (r.success){
|
||
|
|
const pageData = r.body as PageResponse<T>;
|
||
|
|
|
||
|
|
setData(pageData.results);
|
||
|
|
|
||
|
|
|
||
|
|
}
|
||
|
|
else {
|
||
|
|
setData([]);
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
},
|
||
|
|
[data, application, endpoint]
|
||
|
|
)
|
||
|
|
|
||
|
|
// function changePage(pageUrl: string|undefined) {
|
||
|
|
// if (pageUrl){ //TODO CHANGING PAGES
|
||
|
|
// getFetch(`/${application}/${endpoint}/`).then((r)=>{
|
||
|
|
// if (r.success){
|
||
|
|
// const pageData = r.body as PageResponse<T>;
|
||
|
|
//
|
||
|
|
// setData(pageData.results);
|
||
|
|
//
|
||
|
|
//
|
||
|
|
// }
|
||
|
|
// })
|
||
|
|
// }
|
||
|
|
// }
|
||
|
|
|
||
|
|
function nextPage() {
|
||
|
|
// changePage(nextUrl)
|
||
|
|
}
|
||
|
|
|
||
|
|
function previousPage() {
|
||
|
|
// changePage(previousUrl)
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
return {
|
||
|
|
items: data,
|
||
|
|
hasPrevious: undefined,//previousUrl !== undefined,
|
||
|
|
hasNext: undefined,//nextUrl !== undefined,
|
||
|
|
nextPage,
|
||
|
|
previousPage
|
||
|
|
} as PageControl<T>
|
||
|
|
|
||
|
|
|
||
|
|
}
|