diff --git a/src/components/record/record-actions.ts b/src/components/record/record-actions.ts index 5c09f7b..f35a40c 100644 --- a/src/components/record/record-actions.ts +++ b/src/components/record/record-actions.ts @@ -7,15 +7,35 @@ import { JournalRecord, } from '../../services/journal-repository' +function getSavingError(error: unknown): Error { + if (error instanceof Error) { + return error + } + return new Error('Unknown saving error', { cause: error }) +} + +export type SaveRecordProblem = { + recordText: string + error: Error +} + export async function newRecordAction( args: ActionFunctionArgs -): Promise { - const values = Object.fromEntries(await args.request.formData()) - +): Promise { const config = loadConfig() - await createRecord(values.content.toString(), config) + const values = Object.fromEntries(await args.request.formData()) + const recordText = values.content.toString() - return redirect('/') + try { + await createRecord(recordText, config) + return redirect('/') + } catch (err) { + console.error('Failed to save a record', err) + return { + recordText, + error: getSavingError(err), + } + } } export async function recordsLoader(): Promise { diff --git a/src/components/record/record-new.tsx b/src/components/record/record-new.tsx index e1895a8..4351f95 100644 --- a/src/components/record/record-new.tsx +++ b/src/components/record/record-new.tsx @@ -1,14 +1,28 @@ -import { Button, Container, Stack, TextField, Typography } from '@mui/material' +import { + Alert, + Button, + Container, + Stack, + TextField, + Typography, +} from '@mui/material' import React, { useState } from 'react' import { useTranslation } from 'react-i18next' -import { Form } from 'react-router-dom' +import { Form, useActionData } from 'react-router-dom' +import { SaveRecordProblem } from './record-actions' const RecordNew: React.FunctionComponent = () => { - const [content, setContent] = useState('') + const savingProblem = useActionData() as SaveRecordProblem | undefined + const [content, setContent] = useState(savingProblem?.recordText || '') const { t } = useTranslation(['record', 'general']) + const errorAlert = savingProblem ? ( + Saving failed: {savingProblem.error.message} + ) : null + return ( + {errorAlert} {t('New Record')}