react-storage-drafts
Version:
React Drafts is a library for creating, saving, and managing local documents in React applications.
33 lines (32 loc) • 1.64 kB
JavaScript
import { useCallback, useMemo } from 'react';
import useDrafts from './useDrafts';
export default function useDraft(props) {
const { drafts, getDraft, referenceKey, removeDraft, updateDraft } = useDrafts();
const draft = useMemo(() => {
var _a, _b;
if ((props === null || props === void 0 ? void 0 : props.draftId) === 'first') {
return (_a = drafts === null || drafts === void 0 ? void 0 : drafts[0]) !== null && _a !== void 0 ? _a : null;
}
if ((props === null || props === void 0 ? void 0 : props.draftId) === 'last') {
return (_b = drafts === null || drafts === void 0 ? void 0 : drafts[drafts.length - 1]) !== null && _b !== void 0 ? _b : null;
}
return getDraft(props === null || props === void 0 ? void 0 : props.draftId);
}, [getDraft, props === null || props === void 0 ? void 0 : props.draftId]);
const draftId = useMemo(() => {
if ((props === null || props === void 0 ? void 0 : props.draftId) === 'first' || (props === null || props === void 0 ? void 0 : props.draftId) === 'last') {
return draft === null || draft === void 0 ? void 0 : draft[referenceKey];
}
return props === null || props === void 0 ? void 0 : props.draftId;
}, [draft, props === null || props === void 0 ? void 0 : props.draftId, referenceKey]);
const update = useCallback((changes) => {
updateDraft(draftId, changes);
}, [draftId, updateDraft]);
const remove = useCallback(() => {
removeDraft(draftId);
}, [draftId, removeDraft]);
return {
draft,
update,
remove,
};
}