improve: use react-query for caching
This commit is contained in:
56
src/utils/markdown-queries.js
Normal file
56
src/utils/markdown-queries.js
Normal file
@@ -0,0 +1,56 @@
|
||||
import {useQuery, useMutation, useQueryClient} from 'react-query';
|
||||
import {fetch_} from "./request-utils";
|
||||
import config from "../config";
|
||||
|
||||
export const useMarkdown = (id) => {
|
||||
return useQuery(
|
||||
["markdown", id],
|
||||
() => fetch_(`${config.BACKEND_HOST}/api/markdown/${id}`),
|
||||
{
|
||||
enabled: !!id,
|
||||
});
|
||||
};
|
||||
|
||||
export const useIndexMarkdown = (path_id) => {
|
||||
const queryClient = useQueryClient();
|
||||
return useQuery(
|
||||
["index_markdown", path_id],
|
||||
() => fetch_(`${config.BACKEND_HOST}/api/markdown/get_index/${path_id}`),{
|
||||
enabled: !!path_id,
|
||||
onSuccess: (data) => {
|
||||
if(data && data.id){
|
||||
queryClient.setQueryData(["markdown", data.id], data);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const useMarkdownsByPath = (pathId) => {
|
||||
return useQuery(
|
||||
["markdownsByPath", pathId],
|
||||
() => fetch_(`${config.BACKEND_HOST}/api/markdown/by_path/${pathId}`),
|
||||
{
|
||||
enabled: !!pathId
|
||||
});
|
||||
};
|
||||
|
||||
export const useSaveMarkdown = () => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation(({id, data}) => {
|
||||
const url = id
|
||||
? `${config.BACKEND_HOST}/api/markdown/${id}`
|
||||
: `${config.BACKEND_HOST}/api/markdown/`;
|
||||
const method = id ? "PUT" : "POST";
|
||||
return fetch_(url, {
|
||||
method,
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
},{
|
||||
onSuccess: (res, variables) => {
|
||||
queryClient.invalidateQueries(["markdownsByPath", variables.data.parent_id]);
|
||||
queryClient.invalidateQueries(["markdown", variables.data.id]);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user