refactor: simplify form draft key generation
This commit is contained in:
@@ -3,8 +3,6 @@ import { useState, useEffect, useCallback } from 'react';
|
||||
import { useEnterpriseModuleConfigContext } from './use-module.context';
|
||||
import { DraftConfig, FormPageType } from '../entities/entity';
|
||||
import {
|
||||
appStorage,
|
||||
AppStorageKey,
|
||||
appDatabase,
|
||||
AppDatabaseKey,
|
||||
} from '../../../../../../apps/web/src/core/storage/local';
|
||||
@@ -19,36 +17,28 @@ export function useFormDraftContext({ config }: FormDraftContextProps) {
|
||||
const { config: moduleConfig } = useEnterpriseModuleConfigContext();
|
||||
const [hasDraft, setHasDraft] = useState(false);
|
||||
const [draftData, setDraftData] = useState<any>(null);
|
||||
const [userID, setUserID] = useState<string>('UNRESOLVED_PRINCIPAL');
|
||||
|
||||
const isEnabled = config?.enableDraft === true;
|
||||
// Use a generic 'CREATE' key for both CREATE and DUPLICATE so that drafts saved
|
||||
// during DUPLICATE can be restored when entering a new CREATE form.
|
||||
const draftKey = `${userID}:draft:${moduleConfig.moduleKey}:CREATE`;
|
||||
const draftKey = `draft:${moduleConfig.moduleKey}:CREATE`;
|
||||
|
||||
// Check for existing draft on mount
|
||||
useEffect(() => {
|
||||
if (!isEnabled) return;
|
||||
// Fetch user ID asynchronously using appStorage
|
||||
appStorage.getItem(AppStorageKey.USER_ID).then((id: any) => {
|
||||
const resolvedUserId = id || 'UNRESOLVED_PRINCIPAL';
|
||||
setUserID(resolvedUserId);
|
||||
|
||||
const resolvedDraftKey = `${resolvedUserId}:draft:${moduleConfig.moduleKey}:CREATE`;
|
||||
appDatabase
|
||||
.getItem(AppDatabaseKey.OFFLINE_DRAFT)
|
||||
.then((allDrafts: any) => {
|
||||
const drafts = allDrafts || {};
|
||||
if (drafts[resolvedDraftKey]) {
|
||||
setDraftData(drafts[resolvedDraftKey]);
|
||||
setHasDraft(true);
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[Draft Recovery] Failed to read from appDatabase:', err);
|
||||
});
|
||||
});
|
||||
}, [isEnabled, moduleConfig.moduleKey]);
|
||||
appDatabase
|
||||
.getItem(AppDatabaseKey.OFFLINE_DRAFT)
|
||||
.then((allDrafts: any) => {
|
||||
const drafts = allDrafts || {};
|
||||
if (drafts[draftKey]) {
|
||||
setDraftData(drafts[draftKey]);
|
||||
setHasDraft(true);
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[Draft Recovery] Failed to read from appDatabase:', err);
|
||||
});
|
||||
}, [isEnabled, draftKey]);
|
||||
|
||||
const saveDraft = useCallback(
|
||||
(data: any) => {
|
||||
|
||||
Reference in New Issue
Block a user