diff --git a/src/components/ModForm.tsx b/src/components/ModForm.tsx index f539739..e17f646 100644 --- a/src/components/ModForm.tsx +++ b/src/components/ModForm.tsx @@ -31,6 +31,7 @@ import { Editor, EditorRef } from './Markdown/Editor' import { MEDIA_OPTIONS } from 'controllers' import { InputError } from './Inputs/Error' import { ImageUpload } from './Inputs/ImageUpload' +import { useLocalCache } from 'hooks/useLocalCache' interface GameOption { value: string @@ -45,9 +46,18 @@ export const ModForm = () => { const submit = useSubmit() const games = useGames() const [gameOptions, setGameOptions] = useState([]) + + // Enable cache for the new mod + const isEditing = typeof mod !== 'undefined' + const [cache, setCache, clearCache] = useLocalCache('draft-mod') const [formState, setFormState] = useState( - initializeFormState(mod) + isEditing ? initializeFormState(mod) : cache ? cache : initializeFormState() ) + + useEffect(() => { + !isEditing && setCache(formState) + }, [formState, isEditing, setCache]) + const editorRef = useRef(null) useEffect(() => { @@ -145,37 +155,42 @@ export const ModForm = () => { ) const [showConfirmPopup, setShowConfirmPopup] = useState(false) - const handleReset = () => { + const handleReset = useCallback(() => { setShowConfirmPopup(true) - } - const handleResetConfirm = (confirm: boolean) => { - setShowConfirmPopup(false) + }, []) + const handleResetConfirm = useCallback( + (confirm: boolean) => { + setShowConfirmPopup(false) - // Cancel if not confirmed - if (!confirm) return + // Cancel if not confirmed + if (!confirm) return - // Reset fields to the initial or original existing data - const newState = initializeFormState(mod) + // Reset fields to the initial or original existing data + const initialState = initializeFormState(mod) - // Reset editor - editorRef.current?.setMarkdown(newState.body) - setFormState(newState) - } - const handlePublish = () => { - submit(JSON.stringify(formState), { - method: mod ? 'put' : 'post', - encType: 'application/json' - }) - } + // Reset editor + editorRef.current?.setMarkdown(initialState.body) + setFormState(initialState) + + // Clear cache + !isEditing && clearCache() + }, + [clearCache, isEditing, mod] + ) + + const handlePublish = useCallback( + (e: React.FormEvent) => { + e.preventDefault() + submit(JSON.stringify(formState), { + method: isEditing ? 'put' : 'post', + encType: 'application/json' + }) + }, + [formState, isEditing, submit] + ) return ( -
{ - e.preventDefault() - handlePublish() - }} - > + { navigation.state === 'loading' || navigation.state === 'submitting' } > - {mod ? 'Reset' : 'Clear fields'} + {isEditing ? 'Reset' : 'Clear fields'}