Refactor post() and deal with fetched data as a typed interface.

the post() function now uses await syntax rather than .then()
This commit is contained in:
Sheldon Lee 2023-11-23 19:17:45 +08:00
parent 8a1b52749b
commit 1555cf37cd

View File

@ -3,22 +3,27 @@ import '../App.css';
import { useState, useEffect } from 'react';
function Gallery() {
const [data, setData] = useState('');
const [data, setData] = useState<galleryItemInfo[]>([]);
const [category, setCategory] = useState('');
useEffect(() => {
post(category, (json: string) => {
setData(json);
});
post(category, (data: galleryItemInfo[]) => {
setData(data);
});
}, [category]);
const updateCategory = (category: string) => {
setData([]);
setCategory(category);
};
return (
<div className="Gallery">
<div className="Header">
{getContents(data, true, category, setCategory)}
{Contents(data, true, category, updateCategory)}
</div>
<div className="Contents">
{getContents(data, false, category, setCategory)}
{Contents(data, false, category, updateCategory)}
</div>
</div>
);
@ -30,30 +35,21 @@ interface galleryItemInfo {
thumbnail_url: string;
}
function getContents(
data: string,
function Contents(
data: galleryItemInfo[],
getDir: boolean,
category: string,
setCategory: (category: string) => void
) {
if (data === '') return;
if (data === null) return;
let obj = null;
try {
obj = JSON.parse(data);
} catch (error: unknown) {
if (!(error instanceof SyntaxError)) {
throw new Error(error as unknown as undefined);
}
return data;
}
return obj
.sort((a: galleryItemInfo, b: galleryItemInfo) => {
return data
.sort((a: galleryItemInfo, b: galleryItemInfo): number => {
if (a.is_dir && b.is_dir) return 0;
if (a.is_dir && !b.is_dir) return -1;
if (!a.is_dir && b.is_dir) return 1;
if (!a.is_dir && !b.is_dir) return 0;
return 0;
})
.filter((item: galleryItemInfo) => {
return getDir == item.is_dir;
@ -135,8 +131,12 @@ function getFileName(string: string): string {
return string.split('/').at(-1) as unknown as string;
}
function post(category: string, callback: (text: string) => void) {
fetch(
async function post(
category: string,
setDataCallback: (data: galleryItemInfo[]) => void
) {
try {
const response = await fetch(
'http://localhost/photo-viewer-backend/php/get.php',
//'https://dundun.ddns.net/photo-viewer/photo-viewer-backend/php/get.php',
{
@ -148,20 +148,11 @@ function post(category: string, callback: (text: string) => void) {
category: category,
}),
}
)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
);
setDataCallback(await response.json());
} catch (error) {
console.error('Error fetching data: ', error);
}
return response;
})
.then((response) => response.text())
.then((data) => {
callback(data as unknown as string);
})
.catch((error) => {
console.error('There was a problem with the fetch operation:', error);
});
}
export default Gallery;