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

90
src/utils/path-queries.js Normal file
View File

@@ -0,0 +1,90 @@
import { useQuery, useMutation, useQueryClient } from "react-query";
import { fetch_ } from "./request-utils";
import config from "../config";
export const usePaths = (parent_id) => {
const queryClient = useQueryClient();
return useQuery(
["paths", parent_id],
() => fetch_(`${config.BACKEND_HOST}/api/path/parent/${parent_id}`),
{
enabled: !!parent_id,
onSuccess: (data) => {
if(data) {
for (const pth of data)
{
queryClient.setQueryData(["path", pth.id], pth);
}
}
}
}
);
}
export const usePath = (id) => {
const queryClient = useQueryClient();
const cachedData = queryClient.getQueryData(["path", id]);
return useQuery(
["path", id],
() => fetch_(`${config.BACKEND_HOST}/api/path/${id}`),
{
enabled: !!id,
onSuccess: (data) => {
console.log(`path ${id} - ${cachedData}` );
}
}
);
};
export const useCreatePath = () => {
const queryClient = useQueryClient();
return useMutation(
(data) => fetch_(`${config.BACKEND_HOST}/api/path/`, {
method: "POST",
body: JSON.stringify(data),
}),
{
onSuccess: (res, variables) => {
console.log(JSON.stringify(variables));
queryClient.invalidateQueries(["paths", variables.parent_id]);
},
}
);
};
export const useUpdatePath = () => {
const queryClient = useQueryClient();
return useMutation(
({ id, data }) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
method: "PATCH",
body: JSON.stringify(data),
}),
{
onSuccess: (res, variables) => {
queryClient.invalidateQueries(["paths", res.parent_id]);
queryClient.invalidateQueries(["path", variables.data.id]);
},
}
);
};
export const useDeletePath = () => {
const queryClient = useQueryClient();
return useMutation(
(id) => fetch_(`${config.BACKEND_HOST}/api/path/${id}`, {
method: "DELETE",
}),
{
onSuccess: () => {
queryClient.invalidateQueries("paths");
},
}
);
};