kanban-app/frontend/src/hooks/useWikiDetail.ts

106 lines
3.1 KiB
TypeScript
Raw Normal View History

2026-03-22 11:52:33 +00:00
import { useState, useEffect, useCallback } from 'react';
import { useApi } from './useApi';
import { useLoader } from '../context/loaders/useLoader';
import { useToast } from '../context/toasts/useToast';
import type { Wiki, UpdateWikiRequest } from '../types/epic';
function useWikiDetail(wikiId: string) {
const [wiki, setWiki] = useState<Wiki | null>(null);
const [error, setError] = useState<Error | null>(null);
const { getWiki, updateWiki: apiUpdateWiki, deleteWiki: apiDeleteWiki } = useApi();
const { withLoader } = useLoader();
const { addNotification } = useToast();
const fetchWiki = useCallback(async () => {
try {
setError(null);
const data = await withLoader(() => getWiki(Number(wikiId)), 'Loading wiki...');
setWiki(data);
return data;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to load wiki';
setError(err instanceof Error ? err : new Error(errorMessage));
addNotification({
type: 'error',
title: 'Error Loading Wiki',
message: errorMessage,
duration: 5000,
});
return null;
}
}, [wikiId, getWiki, withLoader, addNotification]);
const updateWiki = useCallback(
async (wikiData: UpdateWikiRequest) => {
try {
setError(null);
const updatedWiki = await withLoader(
() => apiUpdateWiki(Number(wikiId), wikiData),
'Updating wiki...'
);
setWiki(updatedWiki);
addNotification({
type: 'success',
title: 'Wiki Updated',
message: 'Wiki updated successfully.',
duration: 3000,
});
return updatedWiki;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to update wiki';
setError(err instanceof Error ? err : new Error(errorMessage));
addNotification({
type: 'error',
title: 'Error Updating Wiki',
message: errorMessage,
duration: 5000,
});
throw err;
}
},
[wikiId, apiUpdateWiki, withLoader, addNotification]
);
const deleteWiki = useCallback(async () => {
try {
setError(null);
await withLoader(() => apiDeleteWiki(Number(wikiId)), 'Deleting wiki...');
addNotification({
type: 'success',
title: 'Wiki Deleted',
message: 'Wiki deleted successfully.',
duration: 3000,
});
return true;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to delete wiki';
setError(err instanceof Error ? err : new Error(errorMessage));
addNotification({
type: 'error',
title: 'Error Deleting Wiki',
message: errorMessage,
duration: 5000,
});
throw err;
}
}, [wikiId, apiDeleteWiki, withLoader, addNotification]);
useEffect(() => {
if (wikiId) {
fetchWiki();
}
}, [wikiId, fetchWiki]);
return {
wiki,
error, // For debugging, not for UI display
loading: false, // Loading is handled by global loader
updateWiki,
deleteWiki,
refetch: fetchWiki,
};
}
export default useWikiDetail;