improve: use react-query for caching

This commit is contained in:
h z
2024-12-08 17:11:14 +00:00
parent a31cec7ef0
commit 0e6fd8409a
15 changed files with 640 additions and 353 deletions

View File

@@ -1,55 +1,38 @@
import React, { useEffect, useState } from "react";
import PermissionGuard from "../PermissionGuard";
import PathNode from "./PathNode";
import config from "../../config";
import "./SideNavigation.css";
import { fetch_ } from "../../utils/requestUtils";
import {useDeletePath, usePaths, useUpdatePath} from "../../utils/path-queries";
const SideNavigation = () => {
const [paths, setPaths] = useState([]);
const [loading, setLoading] = useState(false);
const {data: paths, isLoading, error} = usePaths(1);
const deletePath = useDeletePath();
const updatePath = useUpdatePath();
const handleDelete = (id) => {
fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
method: "DELETE",
},{
use_cache: false,
use_token: true,
}).then(() => {
setPaths((prevPaths) => prevPaths.filter((path) => path.id !== id));
})
.catch((error) => console.error(error));
if (window.confirm("Are you sure you want to delete this path?")){
deletePath.mutate(id, {
onError: (err) => {
alert("Failed to delete path");
},
});
}
};
const handleSave = (id, newName) => {
fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
method: "PUT",
body: JSON.stringify({ name: newName, parent_id: 1 }), // Update with actual parent_id
}, {
use_cache: false,
use_token: true,
}).then(() => {
setPaths((prevPaths) =>
prevPaths.map((path) =>
path.id === id ? { ...path, name: newName } : path
)
);
})
.catch((error) => console.error("Failed to update path", error));
updatePath.mutate({ id, data: {name: newName}} , {
onError: (err) => {
alert("Failed to update path");
}
});
};
if(isLoading){
return <aside className="menu"><p>Loading...</p></aside>;
}
useEffect(() => {
setLoading(true);
fetch_(`${config.BACKEND_HOST}/api/path/`, {},{
use_cache: true,
use_token: false,
})
.then((data) => {
setPaths(data);
})
.catch((error) => console.log(error))
.finally(() => setLoading(false));
}, []);
if(error){
return <aside className="menu"><p>Error...</p></aside>;
}
return (
<aside className="menu">
@@ -63,7 +46,7 @@ const SideNavigation = () => {
</a>
</PermissionGuard>
<ul className="menu-list">
{loading && <p>Loading...</p>}
{isLoading && <p>Loading...</p>}
{paths.map((path) => (
<PathNode
key={path.id}